Home > database >  How to refresh the list of items after submitting a form ReactJS
How to refresh the list of items after submitting a form ReactJS

Time:01-13

Hello I am developing a todo list app using reactjs with axios. I managed to view, and add data to the database, my problem now is that I dont know how to load the updated data after submitting the form.

This is the code for fetching all the data from the database. The file name is FetchData.js

    import { useEffect, useState} from 'react';
import axios from 'axios';

const FetchData = () => {
  const [data, setData] = useState({});
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const fetchData = async () => {
      try {
        const { data: response } = await axios.get('http://localhost/todolistci/backend/index.php/todos/view', { crossDomain: true });
        setData(response);
      } catch (error) {
        console.error(error);
      }
      setLoading(false);
    };

    fetchData();
  }, []);

  return {
    data,
    loading,
  };
};

export default FetchData;

This is how I view the list of items came from FetchData.js. The file name is List.js

import React from 'react';
import ListItem from './ListItem'
import FetchData from './FetchData';

function List() {
  const {
    data,
    loading,
  } = FetchData();

  return (
    <ul>
      {loading && <div>Loading</div>}
      {!loading && (
        <>
          {data.map(item => (<ListItem key={item.id} id={item.id} name={item.name} complete={item.complete} />))}
        </>
      )}
    </ul>
  )
}

export default List

Now this is the form That I am submitting. File name is FormToDo.js

    import React, {useState} from 'react';
import axios from 'axios';

function FormToDo() {
  
    const [formValue, setformValue] = useState({
      name: '',
    });

    const handleSubmit = async(e) => {
      e.preventDefault();
      // store the states in the form data
      const nameFormData = new FormData();
      nameFormData.append("name", formValue.name)
    
      try {
        // make axios post request
        const response = await axios({
          method: "post",
          url: "http://localhost/todolistci/backend/index.php/create",
          data: nameFormData,
          headers: { "Content-Type": "multipart/form-data" },
        });
      } catch(error) {
        console.log(error)
      }

      //empty the text field
      setformValue({name: ''});

      //I need to update the list of data in here
    }
  
    const handleChange = (event) => {
      setformValue({
        ...formValue,
        [event.target.name]: event.target.value
      });
    }

  return (
    <div>
        <form  onSubmit={handleSubmit}>
            <input type="text" name="name" id="name" required placeholder="Enter To Do" 
            value={formValue.name} onChange={handleChange} onKeyDown={handleChange} />
            <button type="submit"> </button>
        </form>
    </div>
  )
}

export default FormToDo

This is the image of the todo app I am making. enter image description here

Please help me. Thank you.

CodePudding user response:

Your example doesn't describe how you are going back to the list after axios posted the data and got a response.

What you need is to mutate after database is updated.

one way could be to move "fetchData" from useEffect to "FetchData" and add a a mutate function that fetches the data and is made available in the return

const FetchData = () => {
  const [data, setData] = useState({});
  const [loading, setLoading] = useState(true);

  const fetchData = async () => {
    try {
      const { data: response } = await axios.get(
        "http://localhost/todolistci/backend/index.php/todos/view",
        { crossDomain: true }
      );
      setData(response);
    } catch (error) {
      console.error(error);
    }
    setLoading(false);
  };

  const mutate = () => fetchData();

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

  return {
    data,
    loading,
    mutate,
  };
};

and then call mutate after data is posted.

A second solution could be to push the browser to the list page and make sure fetchData runs.

A third solution (and the solution I would choose) is to use for example SWR - React Hooks for Data Fetching that would help you to fetch & mutate data, you can see axios example in their docs

  • Related