简体   繁体   中英

Render a functional component after fetching data from a POST API?

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:

  1. I used console.log(labels) in useEffect . and everything is okay with labels array. just the component should be updated.
  2. I used labels array for the deps in useEffect . but it does not worked.

So, which parts are going wrong?

Simply updating the value of a variable won't trigger a render, however if you declare your labels as a state array using the useState() hook updating it will.

Note: Using index as a key is an anti-pattern which will only lead to headaches later, choose a unique identifier for each element to use as key instead.

import React, { useEffect, useState } from "react";
import getCities from "../functions/getCities";
import RadioList from "./RadioList";

export default function ListOfStates(props) {
  const [labels, setLabels] = useState([]);
  const cities = [];

  useEffect(() => {
    getCities(props.cityState).then((array) => {
      for (let i = 0; i < array.response.length; i++) {
        cities.push(array.response[i]);
      }
      setLabels([...cities]);
    });
  }, []);

  return (
    <>
      {labels.length && labels.map((labels, index) =>
        <RadioList active={(labels === props.active)} key={labels.id} label={labels} />)}
    </>
  );
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM