Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to trigger the fetch call in saga?

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

like image 561
bier hier Avatar asked Sep 20 '25 13:09

bier hier


1 Answers

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>
);
like image 163
You Nguyen Avatar answered Sep 23 '25 00:09

You Nguyen