Reputation: 55
I have the following code (using React hooks):
const { state, dispatch } = useContext(Store);
const [branch, setBranch] = useState<TaskingBranchState | null>(null);
const handleBranchChange = (event: ChangeEvent<{}>, newValue: TaskingBranchState | null) => {
setBranch(newValue);
setBranchMembers([]);
}
const [branchMembers, setBranchMembers] = useState([]);
const handleBranchMembersChange = (event: ChangeEvent<{}>, newValue: any) => {
setBranchMembers(newValue);
}
Somewhere later in the code, I'm doing a useQuery
to get the branchMembers
, which is dispatched into my global state
. If it matters, it looks like this:
useQuery(GET_BRANCH_MEMBERS(["id", "name"]), {
variables: {
branchId: branch?.branchId
},
onCompleted: (data) => {
if (data !== undefined && data.getBranchMembers !== undefined && data.getBranchMembers !== state.branchMembers) {
dispatch({
type: 'DISPATCH_TYPE',
payload: {
branchMembers: data.getBranchMembers
}
});
}
}
});
where dispatch
writes the payload
to a global state
(the same state
above in useContext
).
My questions are:
state.branchMembers
(the global value which useQuery
dispatches to) or simply call setBranchMembers
and use the local branchMembers
state defined above?useState
locally (if answering yes to Q1)?Been messing around with my code for a bit and only just realised I had this confusion. Not too familiar with React hooks tbh, so if it's a fundamentals problem, please help as well.
Thank you!
Upvotes: 1
Views: 1268
Reputation: 2866
It depends on whether you would like to share the branchMembers
between different components.
Since you are already dispatching branchMembers
to the global state I assume that you do want to share it. Therefore, you can just go with global state only and remove useState
const { state, dispatch } = useContext(Store);
...
doSomethingWith(state.branchMembers);
...
There is NO NEED to write global state data (from context) to local state (from useState
) in order to use it. You can use data from context right away.
UPDATE
If your branchMembers
depend on branch
then just go ahead and dispatch the branchData
along with branchMembers
. Just remember to write it in the reducer
dispatch({
type: "WRITE_BRANCH_AND_BRANCH_MEMBERS",
payload: {
branch: branchId, // or branch or branchData whatever needed
branchMembers: data.getBranchMembers,
},
});
// your-reducer.js
function reducer(state, action) {
...
switch (action.type) {
case "WRITE_BRANCH_AND_BRANCH_MEMBERS": {
newState = {
...state,
branch: action.payload.branchId,
branchMembers: action.payload.branchMembers,
}
break;
}
...
}
}
Upvotes: 1