How to fetch data instantly after post request - useEffect react

Viewed 128

I want to know if that is the correct way i do it.

Firstly i fetch the hard coded data from my API and display it into the screen. I also have a form from which i send data and i want the axios.get method to instantly fetch the newest updated data that was sent from a form. I made a helper state that is put in to "useEffect array dependencies" and whenever that state changes its value, app reloads and fetches again.

Context file with useEffect hook:

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

import { apiService } from "../services/api/api.service";

const Context = createContext({
  footer: false,
  subjectForm: false,
  storedSubjects: [],
  footerVisibilityHandler: () => {},
  subjectFormVisibilityHandler: () => {},
});

export const ContextProvider = ({ children }) => {
  const [footer, setFooter] = useState(false);
  const [subjectForm, setSubjectForm] = useState(false);
  const [storedSubjects, setStoredSubjects] = useState([]);
  const [send, setSend] = useState(false);

  useEffect(() => {
    const getData = async () => {
      try {
        const getSubjects = await apiService.getSubjects();

        const tableRow = getSubjects.data.map((subject) => {
          return {
            name: subject.name,
          };
        });

        setStoredSubjects(tableRow);
      } catch (err) {
        console.log(err);
      }
    };

    getData();
  }, [send]);

  const footerVisibilityHandler = () => {
    setFooter((previousState) => !previousState);
    setSubjectForm(false);
  };

  const subjectFormVisibilityHandler = () => {
    setSubjectForm((previousState) => !previousState);
  };

  const context = {
    footer,
    subjectForm,
    storedSubjects,
    footerVisibilityHandler,
    subjectFormVisibilityHandler,
    setSend,
  };

  return <Context.Provider value={context}>{children}</Context.Provider>;
};

export default Context;

Form from which i send data:

import Context from "../../store/context";
import FormContainer from "../UI/FormContainer";
import { apiService } from "../../services/api/api.service";
import { useContext, useRef } from "react";

const AddSubject = () => {
  const ctx = useContext(Context);
  const subject = useRef("");

  const sendData = (e) => {
    e.preventDefault();
    ctx.setSend((prevState) => !prevState);
    apiService.addSubject(subject.current.value);
  };

  return (
    <FormContainer show={ctx.subjectForm} send={sendData}>
      <label htmlFor="subject">Subject Name: </label>
      <input type="text" id="subject" ref={subject} />
      <button type="submit">Add</button>
    </FormContainer>
  );
};

export default AddSubject;

Api endpoints file:

import axios from "axios";

const api = () => {
  const baseUrl = "https://localhost:5001/api";
  let optionAxios = {
    headers: {
      "Content-Type": "multipart/form-data",
    },
  };

  return {
    getSubjects: () => axios.get(`${baseUrl}/subjectcontroller/getsubjects`),
   
    addSubject: (subjectName) =>
      axios.post(
        `${baseUrl}/subjectcontroller/createsubject`,
        {
          name: subjectName,
        },
        optionAxios
      ),
   
  };
};

export const apiService = api();

0 Answers
Related