Home > Mobile >  React setState isn't setting state inside useEffect
React setState isn't setting state inside useEffect

Time:03-10

I'm pretty new to hooks and I'm trying to use setState for data I'm getting back from an API, but the state never updates. I only need to make the call when the component mounts, which is why the second argument in my useEffect is an empty array. I can see that I'm getting back the data when I console.log the response, it just isn't being set.

const [routeOptions, setRouteOptions] = useState()

useEffect(() => {
    Axios.get("https://svc.metrotransit.org/NexTrip/Routes?format=json").then(response => {
        const routes = response.data
        setRouteOptions(routes)
    });
}, []);

I then try to map through the data like so:

{routeOptions && routeOptions.map(option => {
                <option>
                    {option.description}
                </option>
            })}

but because my state never got set there's nothing to map through.

I may be missing something super obvious cause I'm not familiar with hooks, so any help is appreciated!

CodePudding user response:

You need to return a value from your .map(). Make sure to give your <option> a unique key prop as well.

Note also that the route property Description has a capital D :)

    <select>
      {routeOptions.map((option) => {
        return <option key={option.Route}>{option.Description}</option>;
      })}
    </select>

here it is all together

import { useState, useEffect } from "react";
import Axios from "axios";

export default function Test() {
  const [routeOptions, setRouteOptions] = useState(null);

  useEffect(() => {
    Axios.get("https://svc.metrotransit.org/NexTrip/Routes?format=json").then(
      (response) => {
        const routes = response.data;
        setRouteOptions(routes);
      }
    );
  }, []);

  if (!routeOptions)
    return (
      <div>
        <p>Loading...</p>
      </div>
    );

  return (
    <select>
      {routeOptions.map((option) => {
        return <option key={option.Route}>{option.Description}</option>;
      })}
    </select>
  );
}

CodePudding user response:

try to use Async-select https://react-select.com/async and make a function that returns an array of pair {label, value} instead of wasting your time stuck here.

  • Related