Как сбросить состояние по кнопке одновременно в двух дочерних компонентах
ссылка на codesandbox
Код
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>
);
};