M
M
Mdmitr2021-01-30 11:10:01
React
Mdmitr, 2021-01-30 11:10:01

How to reset state to initial React?

How to reset the state on a button at the same time in two child components
link to codesandbox

Code

import React from "react";
import "./styles.css";
import { JokeOne } from "./JokeOne";
import { JokeTwo } from "./JokeTwo";

export default function App() {
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
      <hr />
      <JokeOne />
      <hr />
      <JokeTwo />
      <hr />
      <button>Обновить шутки</button>
    </div>
  );
}


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

export const JokeOne = () => {
  const [joke, setJoke] = useState([]);
  const [num, setNum] = useState(1);

  const addToArr = useCallback(
    (data) => {
      setJoke(() => [...joke, data.title]);
    },
    [joke]
  );

  useEffect(() => {
    fetch(`https://jsonplaceholder.typicode.com/todos/${num}`)
      .then((res) => res.json())
      .then((data) => addToArr(data));
  }, [num]);

  const add = () => {
    setNum(() => num + 1);
  };

  return (
    <div>
      <h2>Random Joke One</h2>
      <div>
        {joke.map((item) => (
          <div>{item}</div>
        ))}
      </div>
      <button onClick={add}>Добавить</button>
    </div>
  );
};


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

export const JokeTwo = () => {
  const [joke, setJoke] = useState("");
  useEffect(() => {
    fetch("https://api.chucknorris.io/jokes/random?category=sport")
      .then((res) => res.json())
      .then((data) => setJoke(data.value));
  }, []);
  return (
    <div>
      <h2>Random Joke Two</h2>
      <div>{joke}</div>
    </div>
  );
};

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim Antsiferov, 2021-01-30
@Mdmitr

If such a problem arises, then you need to take the data to a higher level (in this case, in App, plus you can use contexts ) or use the state manager (effector, redux, mobx)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question