3

For some reason my whole page reloads every time it updates the state after it gets it from the database. The page flickers and I end up at the top of the page. Why is this?

I update the entire state in other functions like sort(), that works perfect without reloading. I have put event.preventDefault() in every click handler so that shouldn't be the problem.

One of the great things with using React is to have a smooth UI without reloading so this is annoying.

function App() {
  const [contacts, setContacts] = useState({ items: [] });

  useEffect(() => {
    axios
      .get('http://localhost:5000/')
      .then((result) => {       
        setContacts({ items: result.data });
      })
      .catch((err) => console.log(err));
  }, []);

And this is the function that gets called:

const handleSubmit = (event) => {
    event.preventDefault();

    if (!id) {
      axios
        .post('http://localhost:5000/add/', input)
        .then(() => {
          setInput(emptyState);
        })
        .catch((err) => console.log(err));
    } else {
      axios
        .post(`http://localhost:5000/update/${id}`, input)
        .then(() => {
          props.updateContact(input);
          setInput(emptyState);
        })
        .catch((err) => console.log(err));
    }
    window.location = '/';
  };
Joniverse
  • 45
  • 1
  • 6

1 Answers1

-1

You need to put something in your []. You can see that we passed props.name into the array in the second argument. This will now cause the effect to always run again when the name changes. If you don't pass anything it will always update and will be useless.

  useEffect(() => {
    document.title = `Page of ${props.name}`
  }, [props.name])
ethanille
  • 23
  • 4
  • If i put **contacts** in the **[]** I create an infinite loop that keeps fetching from the database. If I use **axios** without **useEffect** I create the infinite loop again, so the **useEffect** is really important. What would you suggest I put in the **[]**? – Joniverse Aug 31 '20 at 16:04
  • That's logic... if you're putting contact and changing contact in your use effect it will be infinite. Find something that you can put in and after it, it will fetch your data. – ethanille Aug 31 '20 at 16:09
  • "it will always update and will be useless" - This is not true. An empty array as the dependency parameter will cause the effect to only run once when the component mounts. This is absolutely not useless and is intended a lot of the time. – Brian Thompson Aug 31 '20 at 17:12
  • not talked about empty array but an array with contact inside... – ethanille Sep 01 '20 at 06:05