[Redux] Fetching Data on the Route change

Source: Internet
Author: User

We'll learn how to fire a async request when the route changes.

A Mock Server data:

/**/api/index.js * Created by Wanzhen on 7.6.2016.*/Import {v4} from' Node-uuid ';//This is a fake in-memory implementation of something//That would is implemented by calling a REST server.Const Fakedatabase={todos: [{id:v4 (), Text:' Hey ', Completed:true, }, {id:v4 (), Text:' Ho ', Completed:true, }, {id:v4 (), Text:' Let ' s go ', Completed:false,}],};const delay= (ms) = =NewPromise (resolve =SetTimeout (Resolve, MS)); Export Const Fetchtodos= (Filter) = =Delay () then (() = {        Switch(filter) { Case' All ':                returnFakedatabase.todos;  Case' Active ':                returnFakeDatabase.todos.filter (t =!)t.completed);  Case' Completed ':                returnFakeDatabase.todos.filter (t =t.completed); default:                Throw NewError (' Unknown filter: ${filter} '); }    });

We want to replace Localstorge with mock server data and so remove the Localstorge code:

//Configurestore.jsImport {CreateStore} from' Redux '; import Todoapp from'./reducers '; Const Addloggingtodispatch= (store) = ={Const Rawdispatch=Store.dispatch; //If Browser not support Console.group    if(!console.group) {returnRawdispatch; }    return(Action) ={console.group (action.type); Console.log ('%c prev state ', ' Color:gray ', Store.getstate ()); Console.log ('%c action ', ' Color:blue ', action); Const ReturnValue=Rawdispatch (action); Console.log ('%c next state ', ' Color:green ', Store.getstate ());        Console.groupend (Action.type); returnreturnvalue; };}; Const Configurestore= () + ={Const Store=CreateStore (Todoapp); //If in production does not log it    if(Process.env.NODE_ENV!== ' production ') {Store.dispatch=Addloggingtodispatch (store); }    returnstore;}; ExportdefaultConfigurestore;

We want to fetch data inside the component:VisibleTodoList.js.

The good place-to-fetch data is in ' Componentdidmount ' lifecycle:this would fetch the initial data, which only run once.

Thats not enough, we still need if the filter changes, it also need to fetch data, for so we can use another lifecycle ' Componentdidupdate '.

Import {Connect} from ' React-redux '; import {Toggletodo} from‘.. /actions '; import ToDoList from'./todolist '; import {withrouter} from' React-router '; import {Getvisibletodos} from‘.. /reducers '; import React, {Component} from' React '; import {Fetchtodos} from‘.. /api '; class Visibletodolist extends Component {//Fetch data when component MountComponentdidmount () {Fetchtodos ( This. Props.filter). Then (Todos)={Console.log ( This. Props.filter, Todos); })    }    //Check The filter props, when it changes, fetch data againcomponentdidupdate (prevprops) {if( This. Props.filter!==prevprops.filter) {Fetchtodos ( This. Props.filter). Then (Todos)={Console.log ( This. Props.filter, Todos); }}}}} render () {return (            <todolist {... This.props}/>)}}const Mapstatetoprops= (state, {params}) = ={Const filter= Params.filter | | ' All '; //Todos, filter would available in props    return{Todos:getvisibletodos (State, filter), filter,};};//re-assign the VisibletodolistVisibletodolist =withrouter (Connect (mapstatetoprops, {Ontodoclick:toggletodo}) (visibletodolist)); ExportdefaultVisibletodolist;

[Redux] Fetching Data on the Route change

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.