jesetera
jesetera

Reputation: 219

react hooks useState consuming object

I am not sure how to make it correctly so I can pass object to useState

const App = () => {
  const [weatherData, setWeatherData] = useState({data: "", time: ""});

  useEffect(() => {
    axios.get(apiUrl).then(response => {
      setWeatherData({...weatherData, data: response.data, time: timestamp});
    });
  }, []);

  return <div>{weatherData && <Weather data={weatherData.data} />}</div>;
};

when I do the same just with useState() and setWeatherData(response.data) it works fine but I would like to add the time

Upvotes: 0

Views: 491

Answers (2)

Martial Anouman
Martial Anouman

Reputation: 410

Try this:

const App = () => {
    const [weatherData, setWeatherData] = useState(null);

    useEffect(() => {
        async function fetchWeather () {
            const response =  await axios.get(apiUrl)
            setWeatherData({data: response.data, time: new Date().getTime()});
        } 
    
        fetchWeather()
    }, [weatherData]);

    return (
        <>
            {weatherData && <Weather data={weatherData.data} />}
        </>
    );
};

Upvotes: 0

Yaroslav
Yaroslav

Reputation: 110

Have you tried the following:

setWeatherData({
  ...response.data,
  time: timestamp,
});

P.S. Let me know if I understood you correctly.

UPD Other option, if you need to access the current state:

useEffect(() => {
  axios.get(apiUrl).then(response => {
    const timestamp = Date.now().timestamp;
  
    setWeatherData((prevWeatherData) => ({
      ...prevWeatherData,
      data: response.data,
      time: timestamp,
    }));
  });
}, []);

Upvotes: 1

Related Questions