如何在渲染组件之前更新状态?

时间:2020-10-03 14:20:20

标签: javascript reactjs axios react-hooks setstate

我有这个应用程序,可以将“人”添加到“电话簿”中,并且如果该人已经存在,则用户可以更新该人的电话。 但我想知道要解决此人何时被删除的问题(我打开两个标签,然后在一个标签中删除手机,然后尝试在第二个标签中“更新”该电话)

我有一个persons.js处理所有HTTP请求(我正在使用axios) 还有一个PersonNotification.js,它告诉用户电话是“添加”,“更新”还是“不存在” 并且所有主要功能都在App.js

内部

这是我的代码

persons.js

import axios from "axios";
const URL = "http://localhost:3001/persons";

const getPersons = () => {
  return axios.get(URL).then((res) => res.data);
};

const addPerson = (person) => axios.post(URL, person);
// this is where i have the probelm (i think)
const updatePerson = (person, number, setErrMsg) => {
  axios
    .put(`${URL}/${person[0].id}`, {
      name: person[0].name,
      number,
    })
//i wanted the change the state of the App.js from this line after there is an error
    .catch((err) => setErrMsg("err"));
};

const deletePerson = (person) => axios.delete(`${URL}/${person.id}`);

export { getPersons, addPerson, deletePerson, updatePerson };

App.js

import React, { useState, useEffect } from "react";
import {
  getPersons,
  addPerson,
  deletePerson,
  updatePerson,
} from "./services/persons";
import Filter from "./components/Filter";
import Form from "./components/Form";
import Phonebook from "./components/Phonebook";
import PersonNotification from "./components/PersonNotification";
const App = () => {
  const [persons, setPersons] = useState([]);
  const [newName, setNewName] = useState("");
  const [newNumber, setNewNumber] = useState("");
  const [query, setQuery] = useState("");
  const [searchValue, setSearchValue] = useState([]);
  const [notification, setNotification] = useState("");
  const [errMsg, setErrMsg] = useState("");

  // fetching the data from json-server (i,e: db.json)
  useEffect(() => {
    getPersons().then((res) => setPersons(res));
  }, []);
  // function that fires after the submit
  const personsAdder = (e) => {
    e.preventDefault();
    const personsObject = { name: newName, number: newNumber };

    //checking if the name exists
    const nameChecker = persons.filter(
      (person) => person.name === personsObject.name
    );
    console.log(errMsg);
    if (nameChecker.length > 0) {
      const X = window.confirm(
        `${personsObject.name} already exists do you want to update the number`
      );

      if (X === true) {
        // updating the number if the user confirmed
        updatePerson(nameChecker, newNumber, setErrMsg);
        const personsCopy = persons;
        const index = personsCopy.indexOf(nameChecker[0]);
        personsCopy[index] = {
          id: personsCopy[index].id,
          name: personsCopy[index].name,
          number: newNumber,
        };

        setPersons([...personsCopy]);
        setNewName("");
        setNewNumber("");
        //the function the shows the notification for 5 seconds after the content was updated
        const notificationSetter = () => {
          let X = "";
          if (errMsg.length > 0) {
            X = `you can't update${nameChecker[0].name} because it doesn't exist anymore`;
          } else {
            X = `${nameChecker[0].name} was updated`;
          }
          setNotification(X);

          setTimeout(() => {
            setNotification("");
            setErrMsg("");
          }, 5000);
        };
        notificationSetter();
      }
    } else {
      //adding a new user if the name was not already in the phonebook
      setPersons(persons.concat(personsObject));
      addPerson(personsObject);
      setNewName("");
      setNewNumber("");
      //the function the shows the notification for 5 seconds after the content was added
      const notificationSetter = () => {
        setNotification(`${personsObject.name} was added`);
        setTimeout(() => {
          setNotification("");
        }, 5000);
      };
      notificationSetter();
    }
  };

//... there is still more down here; i don't know if i should copy paste all my code

PersonNotification.js

import React from "react";
import "./PersonNotification.css";

const PersonNotification = ({ notification, errMsg }) => {
  if (errMsg.length > 0) {
    return <h1 className="err">{notification}</h1>;
  }
  if (notification.length === 0) {
    return <></>;
  } else {
    return <h1 className="notification">{notification}</h1>;
  }
};

export default PersonNotification;

PS: 此应用程序的github文件夹。 这是来自fullstackopen.com的练习,因此在将问题发布到此处之前,我会有所犹豫,但我在此问题上花费了4个多小时 我只想弄清楚如何更早地更新“ errMsg”的状态,然后我认为一切都会变得简单

1 个答案:

答案 0 :(得分:1)

这部分内容将为您提供进一步的帮助。

persons.js

const updatePerson = (person, number) => {
  const request = axios
    .put(`${URL}/${person[0].id}`, {
      name: person[0].name,
      number,
    });
  return request.then(response => response.data)
};

App.js

if (X === true) {
  const notificationSetter = (X) => {
    setNotification(X);

    setTimeout(() => {
      setNotification("");
      setErrMsg("");
    }, 5000);
  };
  // updating the number if the user confirmed
  updatePerson(nameChecker, newNumber, setErrMsg)
  .then(data => {
    notificationSetter(`${nameChecker[0].name} was updated`);
    console.log('persons :>> ', persons);
    console.log('data :>> ', data);
    
    const personsCopy = persons;
    const index = personsCopy.indexOf(nameChecker[0]);
    personsCopy[index] = {
      id: personsCopy[index].id,
      name: personsCopy[index].name,
      number: newNumber,
    };
    
    setPersons([...personsCopy]);
  })
  .catch(error => {
    notificationSetter(`you can't update ${nameChecker[0].name} because it doesn't exist anymore`);
    getPersons().then((res) => setPersons(res));
  })
  setNewName("");
  setNewNumber("");
}