bearthum
bearthum

Reputation: 117

Pass updated parent state to child props React.js

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

Answers (1)

Goutham J.M
Goutham J.M

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>
  1. You can use useEffect and listen to props and show value only after the correct data comes

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>
    )
}
  1. use Context Api and update state from sibling component(DropDownDifficulty) and pass it to the Questions component

For How to implement in context api refer the code below Edit nervous-wing-6f3nd

Upvotes: 1

Related Questions