I need to call an API in a child component from a grandchild that is a child of another child of the main(parent) component. Here is the structure of my components.
function MainComponent(){
return(
<div>
<Child1Component />
<Child2Component />
</div>
)
}
function Child1Component(){
return(
<div>
<ModalComponent />
</div>
)
}
function ModalComponent(){
const upadate = () => {
//call API in Child2Component
}
return(
<div>
</div>
)
}
function Child2Component(){
const fetch = () => {
axios.get(ULR '/api/mymethod').then(respose =>{
})
}
return(
<div>
</div>
)
}
If there is an update in <ModalComponent/>
that is a child of <Child1Component/>
, an API call should get executed in the <Child2Component/>
so that the Child2Component can get updated, I mean its state should get updated after the API call.
Please anyone could help me with this.
CodePudding user response:
I would create a new component to serve as a parent for child1 and child2. Then moved the API call and the related state to the new parent component. It is called lifting state up.
CodePudding user response:
You have three alternatives:
- Using a shared context in the parent and then pass the state and the set state function respectively to the child and the grandchild. (Best solution in your specific scenario in my opinion)
- Using redux
- Creating a parent state and then pass it directly to children (However, since you have children and grandchildren, it can become messy really fast, so I don't suggest you)
Here the implementation:
//Maincomponent.js
import React, {useState} from 'react';
export const SharedContext= React.createContext(undefined!)
function MainComponent(){
const [myState, setMyState] = useState() //Initialize with anything you want
return(
<SharedContext.Provider value={{myState, setMyState}}>
<div>
<Child1Component />
<Child2Component />
</div>
<SharedContext.Provider/>
)
}
Now let's update the state:
import {useContext} from 'react';
import {SharedContext} from '../my/file/path';
function Child2Component(){
const { myState, setMyState } = useContext(SharedContext);
const fetch = () => {
axios.get(ULR '/api/mymethod').then(respose =>{
//Update parent state through context
setMyState(...) //insert your data
})
}
return(
<div>
</div>
)
}
Finally, let's set a useEffect Hook that listens to changes of the parent state:
import {useEffect, useContext} from 'react';
import {SharedContext} from '../my/file/path';
function ModalComponent(){
const { myState, setMyState } = useContext(SharedContext);
useEffect(()=>{
//Update here. This will be called every time you update parent state
}
,[myState])
return(
<div>
</div>
)
}