简体   繁体   中英

react-admin: dispatch action to store meta data from dynamic request

Hi this question is a continue to this one !

I'm getting my routes dynamically via an ajax request (following this article in the official docs "Declaring resources at runtime"), I'm using an async function to return a list of resources from an ajax request.

What is the best way to dispatch an action to store meta data, which I got form ajax request in redux, for later access?

Also when user has not yet logged in, this function will not return anything, after logging in, user will have access to a couple of resources. What is the best way to reload resources?

To get this to work, I added a private variable, which I store the data mentioned in the question, and I access it via another function, which I exported from that file.

This gives me what I need, but I don't know if it's the best way to go.

The best option is to use redux-saga . https://redux-saga.js.org/docs/introduction/BeginnerTutorial.html

Then

export function* async() {
  yield fetch(); //your Ajax call function
  yield put({ type: 'INCREMENT' }) //call your action to update your app
}

Incase you can't use redux-saga, I like your solution with private variable. You should go ahead with that.

https://github.com/redux-utilities/redux-actions

redux-actions is really simple to setup. Configure the store and then you can setup each state value in a single file:

 import { createAction, handleActions } from 'redux-actions' let initialState = { myValue: '' } export default handleActions({ SET_MY_VALUE: (state, action) => ({...state, myValue: action.payload}) }) export const setMyValue = createAction('SET_MY_VALUE') export const doSomething = () => { return dispatch => { doFetch().then(result => { if (result.ok) dispatch(setMyValue(result.data)) }) } } 

Then in your component you just connect and you can access the state value

 import React from 'react' import PropTypes from 'prop-types' import { connect } from 'react-redux' class MyComponent extends React.Component { render = () => ( <span>{this.props.myValue}</span> ) } MyComponent.propTypes = { myValue: PropTypes.string.isRequired } const mapStateToProps = (state) => ({ myValue: state.myState.myValue }) const mapDispatchToProps = () => ({}) export default connect(mapStateToProps, mapDispatchToProps)(MyComponent) 

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