简体   繁体   中英

Is this the correct way to update the status in react with hook?

first of all sry for my bad english.

I am currently making an application to organize tournaments. I have a ListTournament component that shows the components depending on the sport (prop.sport). What I'm doing is an axios call at the moment the component is created, doing this produces an infinite loop, which I solve by updating the state only if a new sport is selected to the previous one.

Is this the correct way?


import React,{useEffect,useState} from "react";
import Tournament from "./Card";
import "../resources/styles/grid.css";
const axios = require("axios").default;

var selected_sport = ''

export default function ListTournaments(props) {
const [tournaments,setTournaments] = useState([])

  const getTournaments = sport => {
    axios
      .get("https://futbol-back.herokuapp.com/tournaments/sport/" + sport)
      .then(function(response) {
        // handle success
        // tournaments = response.data;
        if (props.sport!= selected_sport){ // This is where I correct the infinite loop
          console.log(selected_sport)
          selected_sport = props.sport
          setTournaments(response.data)

        }
      })
      .catch(function(error) {
        // handle error
        console.log(error);
      })
      .then(function() {
        // always executed
      });
  };

getTournaments(props.sport)

  return (
    <div className="tournamentsWrapper">
      {tournaments.map((tournament, index) => (
        <Tournament
          title={tournament.title}
          description={tournament.description}
          requierements={tournament.requierements}
          date={tournament.date}
          img={tournament.img}
          key={index}
        />
      ))}
    </div>
  );
}


You're almost there, you're doing the correct use of the useState hook, but you need to wrap your function in an useEffect hook, because you're. performing a side effect.

useEffect(() => {
  const getTournaments = async (sport) => {
   axios
   .get("https://futbol-back.herokuapp.com/tournaments/sport/" + sport)
   .then(function(response) {
    // handle success
    // tournaments = response.data;
    if (props.sport!= selected_sport){ // This is where I correct the infinite loop
      console.log(selected_sport)
      selected_sport = props.sport
      setTournaments(response.data)

    }
  })
  .catch(function(error) {
    // handle error
    console.log(error);
  })
  .then(function() {
    // always executed
  });
};

 getTournaments(props.sport);
}, []);

This will assure that your effect will run when the component mounts and it will only run once. All your side effects should go in the use effect

It's better to make api call only once the component get mounted:

useEffect(() => {
  getTournaments(props.sport)
}, [props.sport]}

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