How to pass multiple states through react context api
Provider accepts passing any value so you can paas object here and your values as properties.
<GameContext.Provider
value={{ name: [name, setName], color: [color, setColor] }}
>
{props.children}
</GameContext.Provider>;
and where you are accessing in Child
const { name, color } = React.useContext(GameContext);
const [nameValue, setnameValue] = name;
const [colorValue, setcolorValue] = color;
useReducer is better suited to your case:
import React, { useState, useReducer, createContext } from 'react';
const initialState = {
name: '',
color: '',
startgame: false
}
function reducer(state, action) {
return { ...state, ...action };
}
const GameContext = createContext();
const GameProvider = ({ children }) => {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<GameContext.Provider value={{ state, dispatch }}>
{children}
</GameContext.Provider>
);
};
export { GameContext, GameProvider };
The child component:
import { GameContext } from '../../context/GameContext';
...
const { state: { name, color }, dispatch } = useContext(GameContext);
console.log(name);
console.log(color);
// event handler
const handleChangeName = (event) => {
dispatch({ name: event.target.value });
}
const handleChangeColor = (event) => {
dispatch({ color: event.target.value });
}