Reputation: 117
I have two child components in my parent component with routing set up. Child1 component's button updates state of the parent component and I want to pass the updated version of that state to child2 component as props. The problem is, although the state obviously updates in the parent component(I checked it), it doesn't get passed to the child2 component(the older version of state gets passed instead). I think it's because the getdData
function(in the parent component) executes after the child2 component gets rendered. How can I solve this issue so that correct state gets passed?
Here's the code:
Parent component:
import './App.css';
import Questions from './components/questions';
import DropDownDifficulty from './components/dropDownDifficulty';
import {useState} from 'react'
import axios from 'axios';
import {BrowserRouter as Router, Route, Redirect} from 'react-router-dom'
function App() {
const [data, setdata] = useState([])
const getdData = (values)=>{
setdata(values)
}
return (
<div className="App">
<Router>
<Route exact path='/'>
<DropDownDifficulty sendData={getdData}/>
</Route>
<Route exact path = '/quiz'>
<Questions specs={data}/>
</Route>
</Router>
</div>
);
}
export default App;
Child1 component's button:
<Button disabled={buttonDisabled} className='button' variant="contained" color="primary" onClick={()=>sendData([category, Difficulty])}>
Start Quiz
</Button>
child2 component:
import React from 'react'
import Question from './question'
export default function Questions({specs}) {
console.log(specs)
return (
<div>
</div>
)
}
Upvotes: 2
Views: 90
Reputation: 2194
Simple Solution :
1.Check for Correct value before passing it down to props
<div className="App">
<Router>
<Route exact path='/'>
<DropDownDifficulty sendData={getdData}/>
</Route>
{data?.length > 0 && <Route exact path = '/quiz'>
<Questions specs={data}/>
</Route>}
</Router>
</div>
import {useEffect} from 'react'
import Question from './question'
export default function Questions({specs}) {
const [showIfCorrect,setShowIfCorrect]=useState(false)
useEffect(()=>{
if(specs){
// Check if it is correct
setShowIfCorrect(true)
}
},[specs])
return (
<div>
{showIfCorrect && <div>Correct Question</div>}
</div>
)
}
For How to implement in context api refer the code below
Upvotes: 1