Posts

Showing posts with the label redux

Attach Authorization header for all axios requests

Attach Authorization header for all axios requests I have a react/redux application that fetches a token from an api server. After the user authenticates I'd like to make all axios requests have that token as an Authorization header without having to manually attach it to every request in the action. I'm fairly new to react/redux and am not sure on the best approach and am not finding any quality hits on google. Here is my redux setup: // actions.js import axios from 'axios'; export function loginUser(props) { const url = `https://api.mydomain.com/login/`; const { email, password } = props; const request = axios.post(url, { email, password }); return { type: LOGIN_USER, payload: request }; } export function fetchPages() { /* here is where I'd like the header to be attached automatically if the user has logged in */ const request = axios.get(PAGES_URL); return { type: FETCH_PAGES, payload: request }; } // reducers.js const initi...

React Router + Redux - Dispatch an async action on route change?

React Router + Redux - Dispatch an async action on route change? I have a universal react app that's using redux and react-router. I have several routes as follows: /2016 /2015 /2014 /2013 etc. Each route requires data from an API. Currently, i have the <Link> elements in the Navigation component dispatch an async action onClick , which populates the store with data from the API for that route. <Link> onClick For MVP, i'm just overwriting the post: {} contents in the store with the new post contents when the route changes, that way we get any new content that was on the API. post: {} I've realise that having the action dispatchers on the <Link> buttons isn't optimal, as hitting the back button does not re-trigger the action dispatch to get the content for the previous route. <Link> Is there a way to get React Router to trigger the dispatch action anytime a route change occurs? (Limiting it to listen to a specific set of routes would be a bonus...