1

If this useEffect() runs once (using [] as the second parameter), setTicket(response.data) does not update the value of ticket with data. If I run useEffect() with [ticket] as the parameter, it updates the value of ticket with data, but useEffect becomes an infinite loop.

I need it to run once and update the ticket data. I don't think I understand useEffect() and its second parameter.

What do I do to get the expected result?

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

const EditTicket = (props) => {
  const [ticket, setTicket] = useState("");
  useEffect(() => {
    axios
      .get("http://localhost:4000/tickets/" + props.match.params.id)
      .then((response) => {
        setTicket(response.data);
        console.log({ ticket });
      })
      .catch(function (error) {
        console.log(error);
      });
  }, []);

  return <div>edit</div>;
};

export default EditTicket;
tonytone
  • 37
  • 1
  • 5
  • 1
    That *is* how you use it. But the value bound to ticket won't be updated until *next* time the component gets rendered, so that console.log is pointless. – jonrsharpe Apr 23 '20 at 20:43

1 Answers1

3

ticket is a local const. It will never change, and that's not what setTicket is trying to do. The purpose of setTicket is to tell the component to rerender. On that next render, a new local variable will be created, with the new value.

Your code is already written the way it should be written, except that your log statement is not providing you with any useful information. If you want to see that it rerenders with the new value you could move the log statement to the body of the component.

const EditTicket = (props) => {
  const [ticket, setTicket] = useState("");
  console.log('rendering', ticket);
  useEffect(() => {
    // same as before 
Nicholas Tower
  • 72,740
  • 7
  • 86
  • 98