Home > Enterprise >  How can I update state when data from one state is changed and put into new state
How can I update state when data from one state is changed and put into new state

Time:12-24

So I have a parent component (Weather.jsx) that gets forcast weather from an api and passes it to Forcast.jsx this component just passes the whole data array to Tomorrow.jsx. When the inital data changes it is not updating the lower components, I have an assumption that it is because inside Tomorrow.jsx new state is set and then updated so perhaps it does not change there when new data is passed.

Tomorrow.jsx

This code below is from Tomorrow.jsx and shows how I get the data and update an empty array which is then passed into new state and then mapped over and passed to another component which displays the data.

    const [tomorrowForcast, setTomorrowForcast] = useState([]) // Create empty state to hold tomorrowForcast once extracted
    useEffect(function () {
      const forcastArray = props.tomorrowForcast.list // Get full array from props - Weather.jsx > Forcast.jsx > Tomorrow.jsx
      const date = new Date(); // Get full date
      const date1 = date.getDate(); // Get Day
      const date2 = date1   1 // Add one onto todays day
      const newTomorrowForecasts = []; // Create empty array to hold tomorrows forcast pulled from array below
      forcastArray.forEach(forcast => {
        let get_current_dt = forcast.dt_txt // Get date and time
        let split_dt = get_current_dt.split(" ") // Split date and time
        let get_full_date = split_dt[0] // Get just date
        let get_date = get_full_date.slice(8) // Cut date down to just day
        // Check if tomorrows day is same as array item
        if( get_date ==  date2){     
            newTomorrowForecasts.push(forcast); // If so update empty array
        }
      })
        setTomorrowForcast(newTomorrowForecasts) // Push array to empty state
    }, []);
    // This gets the state maps over it and passes it to child component to display
    const forcasts = tomorrowForcast.map(forcast => {
        let tomorrowObj = {...forcast, identifier: 'tomorrow'}
        // Get time
        const get_dt = forcast.dt_txt
        const split_dt = get_dt.split(" ")
        const get_time = split_dt[1]
        const time = get_time.slice(0, 5)
        return (
            <WeatherBlock {...tomorrowObj} d_or_t={time} />
        )
    })

CodePudding user response:

The use effects dependency array is empty as a result the function get's triggered only once.

You have to add props.tomorrowForcast into the useEffects dependency.

useEffect(function () {
      
}, [props.tomorrowForcast]);
  • Related