M
M
Mdmitr2021-01-30 10:14:53
React
Mdmitr, 2021-01-30 10:14:53

How to reset the state of child components?

How to reset (update) the state of two child components at the same time?
link to codesandbox

Restart useEffect on button click in both components

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 } from "react";

export const JokeOne = () => {
  const [joke, setJoke] = useState("");
  useEffect(() => {
    fetch("https://api.chucknorris.io/jokes/random?category=animal")
      .then((res) => res.json())
      .then((data) => setJoke(data.value));
  }, []);
  return (
    <div>
      <h2>Random Joke One</h2>
      <div>{joke}</div>
    </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)
0
0xD34F, 2021-01-30
@Mdmitr

https://codesandbox.io/s/happy-edison-86gz7?file=/...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question