Pi L
Pi L

Reputation: 59

which hooks we use for update and delete in react?

I am new in React and I wanna asking about lifecycles hooks in react for update/delete because when I delete in my component, it will not deleted until I refresh my page, but when i use componentDidUpdate to re-fetch data, my server keeps refreshing all the time, is that wrong that i use this ? it was work when I re-fetch data on componentDidUpdate

here is my code :

class App {
    state = {
        employee: []
      };

      async fetchData() {
        try {
          const { data } = await axios.get("http://localhost:4000/employee/list");
          this.setState({ employee: data });
        } catch (e) {
          if (e) {
            console.log(e);
          }
        }
      }

      componentDidMount() {
        this.fetchData();
      }

      componentDidUpdate() {
        this.fetchData();
      }

      delEmployee = async id => {
        const url = `http://localhost:4000/employee/delete/${id}`;
        try {
          const { data } = await axios.delete(url);
          this.setState(prev => {
            return {
              employee: [...this.state.employee.filter(el => el.id !== id)]
            };
          });
          console.log(data);
        } catch (e) {
          if (e) {
            console.log(e);
          }
        }
      };
}

so I am here to ask which the best to use Hooks for an update ?am I right to use componentDidUpdate?

Upvotes: 0

Views: 292

Answers (1)

Roy.B
Roy.B

Reputation: 2106

No, this.fetchData in componentDidUpdate calls to setState without any break condition. this will cause you infinite loop, if you want to use componentDidUpdate add a condition

I would have done something like this:

class App {
    state = {
        employee: []
      };

      async fetchData() {
        try {
          const { data } = await axios.get("http://localhost:4000/employee/list");
          this.setState({ employee: data });
        } catch (e) {
          if (e) {
            console.log(e);
          }
        }
      }

      componentDidMount() {
        this.fetchData();
      }

      delEmployee = async id => {
        const url = `http://localhost:4000/employee/delete/${id}`;

        try {
           await axios.delete(url);
           await this.fetchData();

        } catch(e) {
            console.log(e);
        }
      };
}

Upvotes: 1

Related Questions