redux reset props after redirect - javascript

I'm using redux and had problem with this code in my component
componentWillReceiveProps(nextProps) {
if(nextProps.data.deleted_ad){
this.props.history.replace('/')
}
}
The problem with this code is that when I nagivate from '/' to 'ad', this will bring me back to '/' again.
Here's my reducer look like
case 'DELETE_AD_PENDING':
return {
...state,
loading: true
}
case 'DELETE_AD_FULFILLED':
return {
...state,
deleted_ad: action.payload.data.success === true ? true : false
}
case 'DELETE_AD_REJECTED':
return {
...state,
loading: false,
error: action.payload.response.data.error
}
It's partially working, but not after user click into a new ad because nextProps.data.deleted_ad is still true after the redirect.

Try react-router-redux (react-router 4 example) ! It works beautifully. You don't have to worry about such props as is_deleted in your component for redirection - you can keep them but don't use them for redirection (I would use them only for rendering)
You put ALL HISTORY into redux and then act an async action for redirection after a successful action. Like this:
In your component (create form component example with a form on submit):
/* components/Create.js */
import {addMeeting} from "../../store/actions/meetingActions";
class Create extends Component {
....
onSubmit(e) {
e.preventDefault();
this.props.dispatch(addMeeting(this.state.meeting));
}
....
}
In your actions declarations (using thunk middleware):
/* meetingActions.js */
import axios from "axios/index";
import {push} from 'react-router-redux';
export function addMeeting(meeting) {
return function (dispatch) {
dispatch({type: 'ADD_MEETING_STARTED'});
axios.post('/api/meeting', meeting)
.then((res) => {
dispatch({type: 'ADD_MEETING_FULFILLED', payload:res.data})
dispatch(push('/')); // <--- HERE
})
.catch((err) => {
dispatch({type: 'ADD_MEETING_ERROR', payload:err.response.data.errors})
});
}
}
You can see a full example of how it works in my repository of basic MERN CRUD stack SPA right here. The code that is might interest you most is in client/store directory.
This solution has an advantage that you will never associate redirection with a component but with an action instead. You can add a second argument to action addMeeting(meeting, redirectTo) to specify where router should go after action.
redux-logger shows this:
Hope it helped!

Related

What is the best practices for redirecting users in React applications?

I have seen much more cases related to redirecting users in react applications and every case was just a different approach to the solution. There are some cases, where redirecting has occurred in actions like this`
export const someAction = (values, history) => async dispatch => {
const res = await someAsyncOperation(props);
history.push('/home');
dispatch(someAction);
}
In this example history object (form react-router) is being passed in react component. For me, this approach is not acceptable.
There is also a special Redirect from react-router.
After then I have already searched many articles and couldn't just find anything.
So in your opinion, what's the best practice for redirecting and where to handle such kind of processes ?
In React, you usually achieve redirects in the componentDidUpdate of your components.
In the case of async actions, you will check a flag stored in the Redux store, generally a boolean like isFetching, isCreating, isUpdating, etc…, which will be modified by the actions.
Simple example:
class EditUser extends Component {
compondentDidUpdate(prevProps) {
if (prevProps.isUpdating && !this.props.isUpdating) {
// ↑ this means that the async call is done.
history.push('/users')
}
}
updateUser() {
const modifiedUser = // ...
this.props.updateUser(modifiedUser)
// ↑ will change state.users.isUpdating from false to true during the async call,
// then from true to false once the async call is done.
}
render() {
// ...
<button onClick={this.updateUser}>Update</button>
// ...
}
}
const mapStateToProps = (state, props) => ({
userToEdit: state.users.items.find(user => user.id === props.userId)
isUpdating: state.users.isUpdating,
})
const mapActionsToProps = {
updateUser: usersActions.updateUser,
}
export default connect(mapStateToProps, mapActionsToProps)(EditUser)
The next step is usually to add another flag in your Redux store to track if the async calls are successful or not (e.g. state.users.APIError, in which you can keep the error returned by the API). Then you achieve the redirect only if there are no errors.
We mostly redirect a user due to when user logged in or when sign out. For example here's basic requireAuth HOC component to check if user is logged in or not and redirect him to another place.
import React, { Component } from 'react';
import { connect } from 'react-redux';
export default ChildComponent => {
class ComposedComponent extends Component {
componentDidMount() {
this.shouldNavigateAway();
}
componentDidUpdate() {
this.shouldNavigateAway();
}
shouldNavigateAway() {
if (!this.props.auth) {
this.props.history.push('/');
}
}
render() {
return <ChildComponent {...this.props} />;
}
}
function mapStateToProps(state) {
return { auth: state.auth.authenticated };
}
return connect(mapStateToProps)(ComposedComponent);
};
There are two position to check if user is logged in
When the first time that component mount - in componentDidMount()
When user try to sign in , log in or sign out - in componentDidUpdate()
Also in your code sample, history.push is in an action creator. Action creators belongs to redux side. Keep redux & react separate.

Need to Execute Function before render() in ReactJS

I've created a login system with React which stores a session when the user logs in. When the page is reloaded, I have added a function which should check if the session exists and then either setState() to true or to false.
As I'm new to React, I'm not sure how to execute this function. Please see my code below for App.js:
import React from 'react';
import './css/App.css';
import LoginForm from "./LoginForm";
import Dashboard from "./Dashboard";
class App extends React.Component {
constructor(props) {
super(props)
this.state = {
renderLoginForm: true
};
this.handleLoginFormMount = this.handleLoginFormMount.bind(this);
}
handleLoginFormMount() {
this.setState({
renderLoginForm: false
});
}
// Check session function.
checkSession() {
fetch('/check-session', {
credentials: 'include'
})
.then((response) => {
return response.json();
})
.then((sessionResult) => {
if (sessionResult.username) {
console.log('false');
this.setState({
renderLoginForm: false
});
} else {
console.log('true');
this.setState({
renderLoginForm: true
});
}
})
.catch((error) => {
console.log('Error: ', error);
});
}
render() {
checkSession();
return (
<div className="App">
{this.state.renderLoginForm ? <LoginForm mountLoginForm={this.handleLoginFormMount} /> : null}
{this.state.renderLoginForm ? null : <Dashboard />}
</div>
);
}
}
export default App;
Having checkSession() in this position outputs the following in the console when loading the page:
Line 50: 'checkSession' is not defined no-undef
If I put the function outside of the class App extends React.Component {}, then it tells me that I cannot set the state of undefined.
Functional Component: In my case I wanted my code to run before component renders on the screen. useLayoutEffect is a hook provided by React for this exact purpose.
import React, { useLayoutEffect } from "react";
...
const App = () => {
useLayoutEffect(() => {
//check local token or something
}, []);
}
Read More: https://reactjs.org/docs/hooks-reference.html#uselayouteffect
Having checkSession() in this position outputs the following in the console when loading the page:
Line 50: 'checkSession' is not defined no-undef
That's because it's a method, but you're calling it like a freestanding function. The call should be this.checkSession();. But keep reading.
Separately:
The render function must be pure, it cannot have side-effects like changing state. Instead, put any side-effects code in componentDidMount; from the documentation for that lifecycle method:
If you need to load data from a remote endpoint, this is a good place to instantiate the network request.
Be sure that your component renders correctly for the original state (before the session check), as well as for the updated state (after the session check).
More about lifecycle methods and such in the documentation.
Alternately, if this component can't do anything useful without the session, you might move the session check to its parent component, and have the parent only render this child component when it has the session check results.

React dispatching action does nothing

I have a problem when trying to fetch initial data for my app from an api.
My problem is that after the console.log(url) in the action, nothing happens. I see the url in the console, but the rest of the code in getInitialRuns() doesn't seem to be executed, atleast not the way I expect. I get no error messages.
When using Postman, I can succesfully get a response from that API endpoint, so the API should be fine.
I have actions that looks like this:
function requestRuns(){
console.log('request')
return {
type: 'getInitialRuns'
}
}
export function getInitialRuns(){
var url = 'http://localhost:32118/api/Runs';
console.log(url);
return dispatch => {
dispatch(requestRuns())
return fetch(url)
.then(response => response.json().then(body => ({response, body})))
.then(({response, body}) => {
if(!response.ok){
console.log('fail')
}
else{
console.log('success')
}
})
}
The component that calls the action looks like this:
class RunList extends Component{
constructor(props) {
super(props)
}
componentWillMount(){
getInitialRuns()
}
render() {
const {runs, isFetching, error} = this.props
return (
<ul className="run-list">
{runs.map((run) =>
<Run key={run.Id} id={run.Id} date={run.DateString} day={run.Day} distance={run.Distance} duration={run.DurationString} avgpace={run.AvgPaceString} calories={run.Calories}/>
)}
</ul>
)
}
}
RunList.propTypes = {
isFetching: PropTypes.bool.isRequired,
runs: PropTypes.instanceOf(Immutable.List),
error: PropTypes.object
}
function mapStateToProps(state) {
return{
runs: state.runs,
isFetching: state.isFetching,
error: state.error
}
}
export default connect(mapStateToProps)(RunList)
My store is set up like this:
import { createStore, applyMiddleware } from 'redux';
import {composeWithDevTools} from 'redux-devtools-extension';
import runs from './reducers/runs';
import thunk from 'redux-thunk';
export default createStore(runs,composeWithDevTools( applyMiddleware(thunk) ))
And these are my reducers
import Immutable from 'immutable'
let initialState = {
runs: Immutable.List([]),
isFetching: false,
error: undefined
};
export default (state = initialState, action) => {
switch(action.type) {
case 'addRun':
return state.unshift(action.run)
case 'deleteRun':
return Object.assign({}, state, {
runs: state.runs.filter((run) => run.Id !== action.id)
})
case 'getInitialRuns':
console.log('initial')
return Object.assign({}, state, {
isFetching: true
})
case 'getInitialRunsSuccess':
console.log('success')
return Object.assign({}, state, {
isFetching: false,
runs: action.runs
})
case 'getInitialRunsFailure':
return Object.assign({}, state, {
isFetching: false,
error: action.error
})
default:
return state
}
}
In order to dispatch an action on redux, you should provide a mapDispatchToProps function to connect. From redux docs:
(..) You can define a function called mapDispatchToProps() that receives the dispatch() method and returns callback props that you want to inject into the presentational component
const mapDispatchToProps = (dispatch) => {
return {
onTodoClick: (id) => {
dispatch(toggleTodo(id))
}
}
}
I see you are using some advanced libraries like Immutablejs. I suggest
you start with reading the awesome redux documentation as it will take you step by step. And until you're familiar with basic redux concepts, avoid any other library.
Here are some notes i hope are useful for you: (they are taken from redux docs)
Notes
An action object which is a payload of information that send data from your application to your store. It is of this form:
var ADD_TODO = {
type: ADD_TODO,
text: 'Build my first Redux app'
}
It's recommended to name you actions types in Upper case, like ADD_TODO.
dispatch accepts an action object (see the example above).
It is recommended to use action creators which are functions that return an action object. It makes them easily testable and portable
Action creators are usually named in lower case: addTodo().
I hope this helps a bit
You should be returning a new state if you want Redux to notice any state change.
Your reducer cases should look something like that:
return {
...previousState,
newValues
}
'addRun'
return state.unshift(action.run)
should be
return {...state, runs: state.run.unshift(action.run) }
The function getInitialRuns returns a function, so calling it doesn't execute anything of the returned function. Btw I'm not sure executing it would be of any use for your app.
Reducers are synchronous, so if you need to do anything asynchronous you would need a middleware, like redux-thunk or redux-observable.
Flow should be:
State -> Views -> Actions -> Middleware -> Actions -> Reducers -> State and back to Views
Please look at the docs at http://redux.js.org/docs/advanced/AsyncActions.html
Also you can enjoy the excellent free courses on egghead:
https://egghead.io/courses/getting-started-with-redux
https://egghead.io/courses/building-react-applications-with-idiomatic-redux
On github you'll find a lot of material on the courses too.

React Redux with redux-observable use the router to navigate to a different page after async action complete

I am using redux-observable and this is my login epic:
const login = ( action$ ) => {
return action$.ofType(SessionActions.LOGIN_USER)
.flatMap(( {payload} ) => {
return sessionService.login(payload)
.do(payload => {
sessionService.setSession(payload));
// Here I want to redirect the user back to his last location
}).map(result => ({
type: SessionActions.LOGIN_SUCCESS,
payload: result
}));
});
}
But how I am redirecting the user to a different page after the login action success.
What is the redux way to do this?
If you use redux-observable with react-router-redux, you can do any redirections within your epics:
import { ajax } from 'rxjs/observable/dom/ajax';
import { push } from 'react-router-redux';
import NProgress from 'nprogress';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/mergeMap';
export default function login(action$) {
return action$.ofType('LOGIN_USER')
.do(() => NProgress.start())
.mergeMap(payload => (
// Call your login service here, please note that it must be an observable to continue in your epic chain.
Observable.fromPromise(sessionService.setSession(payload))
// This is the redirect you're looking for, it's now became an action thanks to react-router-redux :)
.mapTo(push({ url: '/' }))
.do(() => NProgress.done())
));
}
I have even added a progress indicator for the bonus points :) It's constructed with help from redux-observable's own navigation example
I'm totally new to react/redux, but I face the same problem as you, so I create a small APP with a login page.
// On your Login.JS you could implement the component lifecycle
componentWillReceiveProps(nextProps) {
if (nextProps.isAuthenticated){
this.context.router.push({pathname:'/'});
}
}
So, when your 'action' send to the 'reducer' the type: LOGIN_SUCCESS your going to change the corresponding state and when your component 'receive props' your going to check and redirect. I hope this small example help you.

How to properly make REST calls from ReactJS + Redux application?

I'm using ReactJS + Redux, along with Express and Webpack. There is an API built, and I want to be able to make REST calls -- GET, POST, PUT, DELETE -- from the client-side.
How and what is the properly way to go about doing so with the Redux architecture? Any good example of the flow, in terms of reducers, action creators, store, and react routes, would be extremely helpful.
Thank you in advance!
The simpliest way, is to do it using redux-thunk package. This package is an redux middleware, so first of all, you should connect it to redux:
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from './reducers/index';
const store = createStore(
rootReducer,
applyMiddleware(thunk)
);
This allows you to dispatch async actions along with regular sync actions. Let's create one of them:
// actions.js
export function fetchTodos() {
// Instead of plain objects, we are returning function.
return function(dispatch) {
// Dispatching REQUEST action, which tells our app, that we are started requesting todos.
dispatch({
type: 'FETCH_TODOS_REQUEST'
});
return fetch('/api/todos')
// Here, we are getting json body(in our case it will contain `todos` or `error` prop, depending on request was failed or not) from server response
// And providing `response` and `body` variables to the next chain.
.then(response => response.json().then(body => ({ response, body })))
.then(({ response, body }) => {
if (!response.ok) {
// If request was failed, dispatching FAILURE action.
dispatch({
type: 'FETCH_TODOS_FAILURE',
error: body.error
});
} else {
// When everything is ok, dispatching SUCCESS action.
dispatch({
type: 'FETCH_TODOS_SUCCESS',
todos: body.todos
});
}
});
}
}
I prefer to separate react components on presentational and container components. This approach was perfectly described in this article.
Next, we should create TodosContainer component, which would provide data to presentational Todos component. Here, we are using react-redux library:
// TodosContainer.js
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { fetchTodos } from '../actions';
class TodosContainer extends Component {
componentDidMount() {
// When container was mounted, we need to start fetching todos.
this.props.fetchTodos();
}
render() {
// In some simple cases, it is not necessary to create separate `Todos` component. You can put todos markup directly here.
return <Todos items={this.props.todos} />
}
}
// This function is used to convert redux global state to desired props.
function mapStateToProps(state) {
// `state` variable contains whole redux state.
return {
// I assume, you have `todos` state variable.
// Todos will be available in container component as `this.props.todos`
todos: state.todos
};
}
// This function is used to provide callbacks to container component.
function mapDispatchToProps(dispatch) {
return {
// This function will be available in component as `this.props.fetchTodos`
fetchTodos: function() {
dispatch(fetchTodos());
}
};
}
// We are using `connect` function to wrap our component with special component, which will provide to container all needed data.
export default connect(mapStateToProps, mapDispatchToProps)(TodosContainer);
Also, you should create todosReducer, which will handle FETCH_TODOS_SUCCESS action, and other 2 actions if you want display loader / error message.
// reducers.js
import { combineReducers } from 'redux';
const INITIAL_STATE = {
items: [],
isFetching: false,
error: undefined
};
function todosReducer(state = INITIAL_STATE, action) {
switch (action.type) {
case 'FETCH_TODOS_REQUEST':
// This time, you may want to display loader in the UI.
return Object.assign({}, state, {
isFetching: true
});
case 'FETCH_TODOS_SUCCESS':
// Adding derived todos to state
return Object.assign({}, state, {
isFetching: false,
todos: action.todos
});
case 'FETCH_TODOS_FAILURE':
// Providing error message to state, to be able display it in UI.
return Object.assign({}, state, {
isFetching: false,
error: action.error
});
default:
return state;
}
}
export default combineReducers({
todos: todosReducer
});
For other operations like CREATE, UPDATE, DELETE there is nothing special, they are implementing the same way.
The short answer is:
redux is not an architecture
You can use any library. A lot of people these days use the fetch API directly.
To be able to integrate redux with asynchronous actions (which you need for AJAX), you need to use a library to help. The most popular two are redux-thunk and redux-saga, as others have said.
For a brain-dead simple library that you can drop in to your redux app, you could try redux-crud-store. Disclaimer: I wrote it. You could also read the source for redux-crud-store if you are interested in integrating the fetch API, or another API client, with redux-saga
This is the primary use case for libraries like redux-thunk, redux-saga, and redux-observable.
redux-thunk is the simplest, where you would do something like this:
import fetch from 'isomorphic-fetch'
export const REQUEST_POSTS = 'REQUEST_POSTS'
function requestPosts(subreddit) {
return {
type: REQUEST_POSTS,
subreddit
}
}
export const RECEIVE_POSTS = 'RECEIVE_POSTS'
function receivePosts(subreddit, json) {
return {
type: RECEIVE_POSTS,
subreddit,
posts: json.data.children.map(child => child.data),
receivedAt: Date.now()
}
}
// Meet our first thunk action creator!
// Though its insides are different, you would use it just like any other action creator:
// store.dispatch(fetchPosts('reactjs'))
export function fetchPosts(subreddit) {
// Thunk middleware knows how to handle functions.
// It passes the dispatch method as an argument to the function,
// thus making it able to dispatch actions itself.
return function (dispatch) {
// First dispatch: the app state is updated to inform
// that the API call is starting.
dispatch(requestPosts(subreddit))
// The function called by the thunk middleware can return a value,
// that is passed on as the return value of the dispatch method.
// In this case, we return a promise to wait for.
// This is not required by thunk middleware, but it is convenient for us.
return fetch(`http://www.reddit.com/r/${subreddit}.json`)
.then(response => response.json())
.then(json =>
// We can dispatch many times!
// Here, we update the app state with the results of the API call.
dispatch(receivePosts(subreddit, json))
)
// In a real world app, you also want to
// catch any error in the network call.
}
}
The above example is taken directly from http://redux.js.org/docs/advanced/AsyncActions.html which is really the definitive source for answers on your question.

Categories

Resources