简体   繁体   中英

Request failing when trying to pass in parameters in redux-saga for an api call

The problem is that I am trying to pass in parameters for a api request using redux-saga, but I am getting this error in the browser console: GET https://jsonplaceholder.typicode.com/posts/[object%20Object] 404 . I have already performed console.log(data) in the try block of handleGetPost function, and I getting an object as a response, hence that works just fine. Can anyone point out what am I doing wrong here. Here is the code:

FetchPost.js

  const idRef = useRef(null);
  const dispatch = useDispatch();

  const handleSubmit = (event) => {
    event.preventDefault();
    dispatch(getPost(idRef.current.value));
  };

  return (
    <>
      <input type='text' ref={idRef} name='id' />
      <button type='submit' onClick={handleSubmit}>
        Submit
      </button>
    </>
  );
}; 

getPost.js

const GET_POST = 'GET_POST';

const initialState = {
  post: '',
};

const getPost = (id) => ({
  type: GET_POST,
  id,
});

const fetchPostReducer = (state = initialState, action) => {
  switch (action.type) {
    case GET_POST:
      return { ...state, post: action.id };

    default:
      return state;
  }
};

export { getPost, GET_POST };
export default fetchPostReducer;

sagas.js

export function requestGetPost(id) {
  return axios.request({
    method: 'get',
    url: `https://jsonplaceholder.typicode.com/posts/${id}`,
  });
}

function* handleGetPost(action) {
  try {
    const response = yield call(requestGetPost, action.id);
    const { data } = response;
    yield put(getPost(data));
  } catch (error) {
    console.log(error);
  }
}

export function* watcherSaga() {
  yield takeLatest(GET_POST, handleGetPost);
}

What's happening is that requestGetPost is returning a promise. Since axios.request return type is a promise.

const responsePromise = yield call(requestGetPost, action.id);
const response = yield responsePromise;

I hope this answers your question

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM