How to pass multiple hooks to the value of a context API?

1.5k views Asked by At

I am using multiple hooks within a component and I need to pass the hooks to the value. The react documentation was a little confusing and I don't quite understand how to format that information so that my other component can use it. How can I pass the the hooks to the value so that it is formatted correctly, so that it can be used. Because I think I am doing it wrong Can someone point me in the right direction?

Context API

import React, { useState, createContext } from 'react';


export const OptionsContext = createContext();


export const OptionsProvider = props => {

    const [name, setName] = useState('');
    const [price, setPrice] = useState(0);
    const [amountOfOptions, setAmountOfOptions] = useState(0);
    const [totalAmountSpent, setTotalAmountSpent] = useState(0);
    const [listOfOptions, setListOfOptions] = useState([]);
    const { clock } = new Date().toLocaleDateString();

    return (
        <OptionsContext.Provider value={
            [name, setName],
            [price, setPrice],
            [amountOfOptions, setAmountOfOptions],
            [totalAmountSpent, setTotalAmountSpent],
            [listOfOptions, setListOfOptions],
            clock

        }>
            { props.children}
        </OptionsContext.Provider>
    );
}

Passing the API here 
export default function Inputs() {

    const [name, setName] = useContext(OptionsContext);
    const [price, setPrice] = useContext(OptionsContext);
    const [amountOfOptions, setAmountOfOptions] = useContext(OptionsContext);
    const [totalAmountSpent, setTotalAmountSpent] = useContext(OptionsContext);
    const [listOfOptions, setListOfOptions] = useContext(OptionsContext);
    const { clock } = new Date().toLocaleDateString();

    const handleSubmit = (e) => {
        e.preventDefault()
        e.target.reset();
        addListOfOptions(
            {
                name,
                price,
                amountOfOptions,
                totalAmountSpent
            }
        )

    }

    useEffect(() => {
        setTotalAmountSpent((price * amountOfOptions) * 100)

    });

    const getInputValue = (hookSetter) => (e) => {
        let { value } = e.target;
        return hookSetter(value)
    }

    const addListOfOptions = (lists) => {
        setListOfOptions([...listOfOptions, lists])
    }

    // const deleteItem = () => {
    //     listOfOptions.filter
    // }

    return (
        <div className="formoutputs">
            <form onSubmit={handleSubmit}>
                <input type="text" className="input stockname" placeholder="Enter Stock Symbol" onChange={getInputValue(setName)} />
                <input type="text" className="input stockprice" placeholder="Enter Option Price" onChange={getInputValue(setPrice)} />
                <input type="text" className="input stockamount" placeholder="Enter Number Of Option" onChange={getInputValue(setAmountOfOptions)} />
                <button type="submit" className="btn">Submit</button>
            </form>
            <div className="outputs">
                <table>
                    <tr>
                        <th>Date</th>
                        <th>Stock Name</th>
                        <th>Price Of Option</th>
                        <th>Number Of Options</th>
                        <th>Total Amount Spent</th>
                    </tr>
                    {listOfOptions.map(option => {
                        return (
                            <tr>
                                <td>{clock}</td>
                                <td>{option.name}</td>
                                <td>${option.price}</td>
                                <td>{option.amountOfOptions}</td>
                                <td>${option.totalAmountSpent}</td>
                            </tr>
                        )
                    })}
                </table>
            </div>
        </div>
    )
}
1

There are 1 answers

2
ericgio On BEST ANSWER

You can pass the context value as an object. I'd also recommend creating your own useOptionsContext hook so you don't need to call useContext(OptionsContext):

import React, { createContext, useContext, useState } from 'react';

const OptionsContext = createContext();

export const OptionsProvider = props => {
  const [name, setName] = useState('');
  const [price, setPrice] = useState(0);
  const [amountOfOptions, setAmountOfOptions] = useState(0);
  const [totalAmountSpent, setTotalAmountSpent] = useState(0);
  const [listOfOptions, setListOfOptions] = useState([]);
  const { clock } = new Date().toLocaleDateString();

  const value = {
    name,
    setName,
    price,
    setPrice,
    amountOfOptions,
    setAmountOfOptions,
    totalAmountSpent,
    setTotalAmountSpent,
    listOfOptions,
    setListOfOptions,
    clock,
  };

  return (
    <OptionsContext.Provider value={value}>
      {props.children}
    </OptionsContext.Provider>
  );
}

export useOptionsContext = () => useContext(OptionsContext);

Then use it as follows:

export default function Inputs() {
  const {
    name,
    setName,
    price,
    setPrice,
    amountOfOptions,
    setAmountOfOptions,
    totalAmountSpent,
    setTotalAmountSpent,
    listOfOptions,
    setListOfOptions,
    clock,
  } = useOptionsContext();
  
  ...
}