I created my first saga , somehow it does not get triggered:
function* getData() {
console.log("getData");
const json = yield fetch("https://jsonplaceholder.typicode.com/users").then(
response => response.json()
);
yield put({ type: "RECEIVED_DATA", json: json.data });
}
export default function* rootSaga() {
console.log("rootSaga call");
yield takeEvery("GET_DATA", getData);
}
How can I trigger the saga to call the fetch? Codepen
This is the working as expected project: https://codesandbox.io/s/8l8l59wwp9
I've just fixed it. The details explanation will be available soon.
Firstly, for some reason, I don't know why console.log()
method does not work in your project, you might use alert()
method instead.
Secondly, your getDate()
generator function should be like this:
function* getData() {
console.log("getData");
const json = yield call(() =>
fetch("https://jsonplaceholder.typicode.com/users")
.then(response => response.json())
.then(myJson => myJson)
);
yield put({ type: "RECEIVED_DATA", json: json });
}
Thirdly, in your reducer, we should get the value of json
property instead of data
property of the action object.
...
case "RECEIVED_DATA":
return action.json;
...
Finally, I've made some changes in your codes in order to display the results:
// index.js
function render() {
ReactDOM.render(
<Users data={store.getState()} getData={() => action("GET_DATA")} />,
document.getElementById("root")
);
}
// and
// Users.js
const Users = ({ data, getData }) => (
<div>
hi from users
<button onClick={() => getData()}>Get data</button>
<ul>{data.map(user => <li key={user.id}>{user.name}</li>)}</ul>
</div>
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With