0

The useEffect below renders, fetches data, and displays it once (using an empty array for 2nd parameter in useEffect).

I need it to rerun useEffect everytime the user changes data to the database (when user uses axios.post).

What i've tried

  • using [tickets], but that just causes the useEffect to run infinitly
  • also using [tickets.length] and [tickets, setTickets]
  • trying to use props as parameter but didnt find anything useful

 

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

export const TicketContext = createContext();

export const TicketProvider = (props) => {
  console.log(props);
  const [tickets, setTickets] = useState([]);
  useEffect(() => {
    getTickets();
    console.log("1", { tickets });
  }, []);

  const getTickets = async () => {
    const response = await axios.get("http://localhost:4000/tickets/");
    setTickets(response.data);
  };
  return <TicketContext.Provider value={[tickets, setTickets]}>{props.children}
  </TicketContext.Provider>;
};
import React from "react";
import { useState, useEffect, useContext } from "react";
import Ticket from "../Ticket";
import { TicketContext } from "../contexts/TicketContext";

import AddBacklog from "../addData/AddBacklog";

const TicketDisplay = (props) => {
  const [tickets, setTickets] = useContext(TicketContext);

  return (
    <div className="display">
      <p>Antony Blyakher</p>
      <p>Number of Tickets: {tickets.length}</p>
      <div className="backlog">
        <h1>Backlog</h1>
        {tickets.map((currentTicket, i) => (
          <div className="ticketBlock">
            <Ticket ticket={currentTicket} key={i} />
          </div>
        ))}
      </div>
    </div>
  );
const AddBacklog = (props) => {
  const [tickets, setTickets] = useState("");

...

    axios.post("http://localhost:4000/tickets/add", newTicket).then((res) => console.log(res.data));

    setTickets((currentTickets) => [...currentTickets, { name: name, status: "backlog", id: uuid() }]);

  };
tonytone
  • 37
  • 1
  • 5
  • what data is changed by the user? – kyun Apr 28 '20 at 02:28
  • axios.post("http://localhost:4000/tickets/add", newTicket).then((res) => console.log(res.data)); setTickets((currentTickets) => [...currentTickets, { name: name, status: "backlog", id: uuid() }]); – tonytone Apr 28 '20 at 02:33
  • i edited the post to show the add ticket function – tonytone Apr 28 '20 at 02:35
  • when you called `/tickets/add` and then you wanna call `/tickets/`? using `useEffect()`? – kyun Apr 28 '20 at 02:39
  • i dont understand your question, could you please clarify? – tonytone Apr 28 '20 at 02:44
  • 1. call the API `/tickets/add` 2. call the API `/tickets/` with `useEffect()` is that you want? – kyun Apr 28 '20 at 02:45
  • why call getTickets() in useEffect when setTickets will cause a re-render when a new ticket is added to tickets? is there really a need to fetch all tickets again when the only change is the addition of the new ticket? – user3366943 Apr 28 '20 at 14:46

2 Answers2

1

You'll need to watch for tickets and return if it has data to not cause infinite loop:

useEffect(() => {
  if (tickets.length) return // so, we call just once
  getTickets();
  console.log("1", { tickets });
}, [tickets]);
Bhojendra Rauniyar
  • 83,432
  • 35
  • 168
  • 231
0
const fetchData = () => {
axios.get("http://localhost:7000/api/getData/").then((response) => {
  console.log(response.data);
  if (response.data.success) {
    SetIsLoading(false);
  }
  setDataSource(response.data.data);
});
};


useEffect(() => {
fetchData();
if (fetchData.length) fetchData();
}, [fetchData]);

by this you can fetch the data in real-time as any change in data occurs.

  • Hello! While this code may solve the question, [including an explanation](https://meta.stackexchange.com/q/114762) of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please [edit] your answer to add explanations and give an indication of what limitations and assumptions apply. – Brian61354270 Feb 02 '21 at 19:17