Good
Good

Reputation: 81

Add a new value inside the State object in React Hook

I have a data and I put it in the state and I want to add a new value in addition to the content of the data in the object called watched, but this is a problem, thank you for your help.

import React, { useEffect, useState } from "react";
import ListManager from "./component/manager";

const App = () => {
  const [getMovies, setMovie] = useState([]);
  const [getLoading, setLoading] = useState(true);
  useEffect(() => {
    fetch("http://my-json-server.typicode.com/bemaxima/fake-api/movies")
      .then((response) => response.json())
      .then((response) => {
        setMovie(response);
        setLoading(false);
      });
  });
  useEffect(() => {
    return () => {
      setMovise(
        getMovies.map((item) => ({
          id: item.id,
          text: item.name,
          rate: item.rate,
          watched: false,
        }))
      );
    };
  });

  if (getLoading) {
    return "Please wait...";
  }
  return <ListManager movies={getMovies} />;
};

export default App;

Upvotes: 0

Views: 65

Answers (2)

Thomas Boittin
Thomas Boittin

Reputation: 54

  1. It looks like you have a typo calling setMovise instead of setMovies.

  2. I'm not sure about your second useEffect. A return in useEffect is often used for a cleanup function like this (from ReactJS documentation):

    useEffect(() => {
      const subscription = props.source.subscribe();
      return () => {
        // Clean up the subscription
        subscription.unsubscribe();
      };
    });
    

    I'd just put it normally in the code outside the hook before the return statements.

  3. Your variable naming doesn't fit the usual convention for useState.

    const [getMovies, setMovie] = useState([]);
    

    should be

    const [movies, setMovies] = useState([])
    

Upvotes: 0

Soufiane Boutahlil
Soufiane Boutahlil

Reputation: 2604

You don't need the second useEffect, you should use the first useEffect to do all your stuff, also you should pass an empty array to useEffect in order to be executed one time.

  import React, { useEffect, useState } from "react";
    import ListManager from "./component/manager";
    
    const App = () => {
      const [getMovies, setMovie] = useState([]);
      const [getLoading, setLoading] = useState(true);
      useEffect(() => {
        fetch("http://my-json-server.typicode.com/bemaxima/fake-api/movies")
          .then((response) => response.json())
          .then((response) => {
            setMovie(response.map((item) => ({
              id: item.id,
              text: item.name,
              rate: item.rate,
              watched: false,
            })));
            setLoading(false);
          });
      }, []);
    
      if (getLoading) {
        return "Please wait...";
      }
      return <ListManager movies={getMovies} />;
    };
    
    export default App;

Upvotes: 2

Related Questions