I am workin on a project with React and I need to update react state with react hook when new data is inserted to my database. I am using contextAPI but as far as I am concerned, the way my components are structured I can't update that state with the data I got back from my database. Here is the more detail with my code:
I have a component in which data exists with useState
const [questions, setQuestions] = useState([]);
useEffect(() => {
(async () => {
const resp = await axios.get(
`${process.env.REACT_APP_BACKEND_URL}/product/${productId}/question`
);
setQuestions(resp.data);
})();
}, []);
And I have another component called PostQuestion which sends post request to my backend and insert new question to my database. They are completely unaware of each other's existence. we can pass down the props to the children and nested children by using contextAPI. but PostQuestion component is not the child of that component where all the questions data exist. That's how I understand contextAPI. But both of them are children of another component. But I don't want to place my
const [questions, setQuestions] = useState([]);
in that component which is the parent of those two components. What can I do to update that questions state inside my PostQuestion component?
Here is my PostQuestion component code
const postQuestionHandler = async (e) => {
e.preventDefault();
try {
const resp = await axios({
url: `${process.env.REACT_APP_BACKEND_URL}/product/${productId}/question`,
method: "POST",
data: {
question: questionInput.question.value,
userId,
},
});
if (resp.status === 200) {
setShowForm(false);
}
} catch (err) {
alert(err);
}
};
return <SecondaryBtn disabled={questionInput.question.error}>
Submit Your Question
</SecondaryBtn>
Summary
I have 2 components which don't have parent to child relationship. I want to update the state in component 1 by calling setState when I got back new data in component 2. I don't want to have state in those two components parent because it is already cluttered enough.
If I use Redux, there will be no such problem. Perhaps there is a way to do it in contextAPI too.