I want to re-render my component after the data fetched from my API. I used hooks to handle that. but it does not working. actually my component renders for the first time, not after fetching data!
I have an external function. By this function, I can give a province name to that and then receive a list of the cities which they are in that province. my function is like below:
const axios = require('axios');
export default async function getCities(state) {
let res = [], err;
try {
await axios.post('someUrl', {
ProvinceUser: state,
}).then(function (response) {
if (response.status === 200) {
for (let i = 0; i < response.data.length; i++)
res.push(response.data[i].CityUser);
}
}).catch(function (error) {
err = error;
});
} catch (error) {
err = error;
}
return {
response: res,
error: err
}
}
I'm using the above function in my component like below:
import React, {useEffect} from "react";
import getCities from "../functions/getCities";
import RadioList from "./RadioList";
export default function ListOfStates(props) {
let labels = [],
cities = [];
useEffect(() => {
getCities(props.cityState).then((array) => {
for (let i = 0; i < array.response.length; i++)
cities.push(array.response[i]);
labels = cities;
});
}, []);
return (<>
{labels.map((labels, index) =>
<RadioList active={(labels === props.active)} key={index} label={labels}/>)}
</>);
}
It's good to say:
- I used
console.log(labels)
in useEffect
. and everything is okay
with labels
array. just the component should be updated.
- I used
labels
array for the deps in useEffect
. but it does not
worked.
So, which parts are going wrong?
question from:
https://stackoverflow.com/questions/65864963/render-a-functional-component-after-fetching-data-from-a-post-api 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…