score:2
if you are needing route specific variables then its probably easiest (and best practice) to use the route params to initialize state and rerun actions.
if you use class based components loaduser(userid)
will need to be in both componentdidmount
and componentdidupdate
.
for functional components there is react hook useeffect() instead (which seems to be becoming best/better practice these days).
for example:
if you are using react-router-dom in your routes.js/app.js you will have a route such as:
<route path='/some/path/:userid' component={somecomponent}/>
then use props.match.params and useeffect with the userid as a dependency:
import react , {useeffect} from 'react'
import {connect} from 'react-redux'
import * as actions from 'path/to/redux/actions'
// destructure `match.params.userid`, redux `user` and redux action `loaduser` from props
const somecomponent = ({ match:{params:{userid}} , user , loaduser}) => {
useeffect(()=>{
userid && loaduser(userid)
},[loaduser , userid]) // runs after first mount and every time userid changes
return <div>{user && user.id}</div>
}
connect(
({user})=>({user}),
actions
)(somecomponent)
score:0
so first in your container component(any page/route) you can get the query string from the url and update the redux state accordingly
example:
import querystring from 'querystring';
const app (props){
//semulate the component did mount behavior
useeffect(()=>{
const {
active_section,
tab,
//or what ever
} = querystring.parse(history.location.search.replace('?', ''));
props.updatestore({
active_section,
tab
})
},[])
export default connect(app)
score:0
i think you can make use of switch and route components where you can decide the url and params to be passed to the component. once you're done with this then you can decide in the component itself to update the state in store.
but for initializing the store you can pass the generic state i.e. an empty state object or your home page state.
hope this helps!!
score:0
this example uses import { record } from immutable
to save the initial state. if you want to update that from a query string, then you would call an action to update the state just like anything else. i would probably call the action in the constructor or componentdidmount()
.
/*
*
* coursecontainer reducer
*
*/
import { record } from 'immutable';
import {
fetch_course_from_querystring,
fetch_course_from_querystring_success
} from './constants';
const coursecontainerrecord = record({
course: {
coursetitle: '',
ahecid: '',
seatsremaining: 0,
price: 0,
hidden: true,
canceled: false,
objectives: '',
credithours: '',
description: '',
},
coordinators: [],
});
export const initialstate = new coursecontainerrecord({});
function coursecontainerreducer(state = initialstate, action) {
switch (action.type) {
case fetch_course_from_querystring_success:
// ... code
default:
return state;
}
}
export default coursecontainerreducer;
/*
*
* coursecontainer actions
*
*/
import toastr from 'toastr';
import {
fetch_course_from_querystring,
fetch_course_from_querystring_success,
} from './constants';
// #region get course
export function fetchcoursefromquerystring(courseid) {
return {
type: fetch_course_from_querystring,
courseid,
};
}
export function fetchcoursefromquerystringsuccess(course) {
return {
type: fetch_course_from_querystring_success,
course,
};
}
edit i can add an example of dispatching if you need one.
Source: stackoverflow.com
Related Query
- ReactJs - Initialize Redux Store from URL query parameters
- Express js - cannot get query parameters from url (req.query is an empty object)
- ReactJS - Can't obtain parameters from url using Route. How can I pass params through url with Route?
- How to use query parameters from a URL in MapStateToProps
- Can't get parameters from url with Redux ownProps
- Restore Redux store from Angular app in ReactJS application
- How to store the page number in ReactJS (not in state) to construct the GET URL with page number from 1 to 5
- How do you get URL parameters from react-router outside components to use in GraphQL query
- How to replace a string in parameters from query with variables in ReactJS
- React apollo default query variable from redux store
- Initialize Redux Toolkit store via url params on Next 12+ SSR
- How to query from mongo db in react based on URL parameters
- how to use initialize value we obtained from the url in reactjs
- Getting query parameters from react-router hash fragment
- While debugging, can I have access to the Redux store from the browser console?
- useSelector not updating when store has changed in Reducer. ReactJS Redux
- Accessing Redux Store from routes set up via React Router
- Display an image from url in ReactJS
- React get state from Redux store within useEffect
- How to properly make REST calls from ReactJS + Redux application?
- How to update the Redux store after Apollo GraphQL query returns
- How to reset state of Redux Store when using configureStore from @reduxjs/toolkit?
- How to unsubscribe from redux store when component will unmount? How to decorate redux connect?
- ReactJS - get json object data from an URL
- How can I get the URL address from the browser in ReactJS (servers URL)
- Javascript Redux - how to get an element from store by id
- React Native: HeadslessJS and Redux - How to access store from task
- moving from twig to ReactJS: how to extend a template/component to build full reactJS pages? implement react-router and redux into symfony?
- How to connect to redux store from react-router onEnter hook?
- Redux Toolkit RTK Query sending query parameters
More Query from same tag
- exporting react class with AJAX
- reactjs select radio input based on the props
- Is there a simple way to include a JSX file with script tag?
- Baffling syntax error
- How to convert an array of dictionaries into an array of keys using react
- Split parsed rss results
- React state and conditional rendering
- React functional component static property
- Why there is a delay on visualization?
- ant d select from array, react, js
- Hook requires data from another hook, but getting Error: Rendered more hooks than during the previous render
- How do I use an SVG in React without using dangerouslySetInnerHTML?
- Array of components in ReactJS
- Having problem to desctructure my data on React
- C3 Chart bar with percentage
- setstate is causing Too many re-renders
- Property 'context' is missing in type '{ instance: any; }' but required in type 'LeafletElement<Evented, any>'
- How to fixed the table header?
- Mixing native code with react-native
- How to make sure map is loaded with google-map-react
- How to fix TypeScript React props types when passing components as variables?
- How can I test google.maps.Geocoder?
- How to change Ag Grid border color?
- how to load images from a local directory and display them in reactjs app?
- How can I ignore TypeScript errors when adding script tags via react-helmet?
- How to split a Formik / React form into different columns in a table?
- Scroll to a particular div using id in reactJs without using any other library
- Return React component as object value and bind props to it
- React and Parallax : Misplaced parallax image when clicking on in-page navigation link
- Rendering different youtube videos on button click