Murakami
Murakami

Reputation: 3760

Download file using redux flow

Could not find any example describing it.

I'm trying to create download button using react app but going through redux, ie. in action I'm connecting to url and getting the file in response (code 200).

export function sendTimeline(token, timelineObj) {
  const request = axios.post(`muURLGoesHere`, timelineObj, {
    headers: {
      "Content-Type": "application/vnd.ms-excel",
      "X-Accept-Version": "v1",
      Authorization: `Bearer ${token}`
    }
  });

  console.log(request);

  return {
    type: constants.actionTypes.TIMELINE_DATA,
    payload: request
  };
}

How can I pass it to reducer and download it on the react side.

You maybe know the article with an example or any hint on that.

Thank you

Upvotes: 1

Views: 1972

Answers (1)

philipp
philipp

Reputation: 16515

I wouldn't dispatch actions with promised as payload. Use redux-thunk additionally to do more fine grained dispatch of successive actions:

const sendTimeline = (token, timline) => dispatch => {
  dispatch({ type: 'sendtimeline/start' })

  return fetch(…)
    .then(res => res.json())
    .then(json => dispatch({
      type: 'sendtimeline/success',
      payload: json
     }))
    .catch(err => dispatch({
      type: 'sendtimeline/error',
      payload: err,
      error: true
     }))
}

That way you do not have to deal with async problems in the reducer, since the actions handle that. Also you can do stuff like:

this.props.sendTimeline(…).then(…)

when used within a component, since the promise is returned from the action creator.

Have a look here as well

Upvotes: 1

Related Questions