Search code examples
javascriptreactjsstatereducers

React +getting value from queryString


Am facing some difficulty in fetching params from query String.

I have a reducer function which is setting initial value as

const initialState = {
  data: {
    loadedData: false,
    token: '',
    video_thumbnail_url: '',
  }
  mediaToken: '',
  mediaUrl: '',
};

mediaToken value is something I might need to get from queryString and if no it should be empty string

so what basically expecting is mediaToken will be calling a function which will be checking queryString and if not it will pass empty string

For example : https:// localhost:8080/?text=abc&query=multi.....

I need to get the query value from query string and bind it to mediaToken in intialState

example

**mediaToken : function() ( function will be returning either query value from url or if noy present empty string**

and 

const function => {
   // get query value from query string 
   return that
   else return ''
}

Still if you guys dont get my question , please feel free to comment, am happy to reply (sorry for that)


Solution

  • If you are fine with using external node module for achieving this, I would suggest using query-string. This is how you can extract query params using it:

    const queryString = require('query-string');
    
    // ..
    // ..
    // Business logic
    
    let qsJSON = queryString.parse(location.search)
    mediaToken = qsJSON ? qsJSON.[<qs_name>] || '' : ''