DEV Community

Discussion on: React Context with useReducer and Typescript.

Collapse
 
utshp08 profile image
reymart

Finally, I've found the exact thing that I was looking for. However, I still have a question. Can you show me how to initialize state from child nodes using this approach. What I wanted to achieve is something that is similar on this:
const [state, dispatch] = useReducer(
SampleReducer,
initialState,
() => {
return { field1: sampleValue1, field2: sampleValue2}
}

)

Thank you in advance.

Collapse
 
elisealcala profile image
Elizabeth Alcalá

Hey, I'm glad this helps you, according to react docs you can initialize a state passing a third argument. reactjs.org/docs/hooks-reference.h....

Collapse
 
utshp08 profile image
reymart

Yup, it same as what I also mentioned above. But, how would you achieve it in a context since the reducer is already part of the context?

Thread Thread
 
elisealcala profile image
Elizabeth Alcalá

oh. maybe you can pass the function through the context to the reducer? I'm going to try it and if I'm able to do it, I'll share the code :)

Thread Thread
 
utshp08 profile image
reymart

Yup, looking forward to it. That is what I wanted to achieve, I saw also in hooks document that we can create an init function that can be call through dispatch, however, not yet tried it.