I'm trying to pass some fetched data to another component when routing the page using history.push() but it's not passing due to some async/sync issue according to my knowledge. How to solve this
this is the data fetching(using Axios) and data passing component
import React, {useState} from 'react'
import {analyse} from '../../services/dataFetching';
function testFunction() {
const [data, setData] = useState([]);
const fetch = () =>{
analyse() // this the axios based function which is defined in the service class
.then(response => {
setData(response)})
.then(
history.push({
pathname: '/somepage',
state:data}))
.catch(error =>{
console.log(error) })};
return (
<div> <button onClick={fetch}>FETCH DATA</button> </div>
)
}
export default testFunction
in the above class, it is fetching data and it can be logged in the console.
here the data receiving child component
import React from 'react';
import { useLocation } from "react-router-dom";
function testFunction2() {
const { state } = useLocation();
console.log("state: ", state)
return (
<div>
{state}
</div>
)
}
export default testFunction2
to here it is always receiving an empty array
This is because the function returned by the useState call doesn't return a promise, ie) setData isn't a promise, so it is resolved instantly, causing the next step in the chain, which is history.push(), to be called immediately without waiting for setData() to finish execution. What you want to do here is have history.push() execute after your state is set, which can be done using the useEffect() hook.
import React, {useState, useEffect} from 'react'
import {analyse} from '../../services/dataFetching';
function testFunction() {
const [data, setData] = useState([]);
useEffect(()=>{
history.push({
pathname: '/somepage',
state:data})
},[data])
const fetch = () =>{
analyse() // this the axios based function which is defined in the service class
.then(response => {
setData(response)})
.catch(error =>{
console.log(error) })};
return (
<div> <button onClick={fetch}>FETCH DATA</button> </div>
)
}
export default testFunction
Now, the function specified in the useEffect hook will be called whenever the data variable is modified, which happens when the state is successfully set.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.