4
    componentDidMount() {
  var value =  AsyncStorage.getItem('name');
value.then((e)=>{
  this.setState({
   name: e.name
  })
})
const namme = encodeURIComponent(this.state.name);
      return fetch('http://www.example.com/user-list.php?name=${name}' , {
       method: 'POST',
       headers: {
         'Accept': 'application/json',
         'Content-Type': 'application/json',
       }

I am still learning React Native and I was wondering if this is the correct way to pass parameters in the URL? I also heard about using Redux to help with this, but I don't know how to exactly implement that.

1
  • I would create a separate question on how to implement this in redux.
    – ajthyng
    Commented Feb 7, 2018 at 2:46

2 Answers 2

2

This is not correct. AsyncStorage is an API bundled with react native that allows you to store data on the user's device. You can read more about it over at Facebook's documentation.

You are somewhat close though, if you want to fetch data asynchronously the documentation for React Component lifecycle events say to use componentDidMount()

Here is how I would fetch the remote data using

componentDidMount() {
  const fetchConfig = {
    method: 'POST',
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json'
    }
  };
  fetch(`http://www.example.com/user-list.php?name=${name}`, fetchConfig)
    .then(res => res.json())
    .then(e => {
      this.setState({ name: e.name });
    });
}

A couple things to note here: the url string is using backticks, not single quotes. It's called a template literal.

Also, fetch is returning a promise. Fetch makes you do the work of knowing what type of data your request is returning. In order to parse the JSON into a JavaScript object you call res.json() which returns a promise to the next then block. Once that promise resolves you can then set your state based on the object returned.

2
  • Thank you, but I am getting an error: Can't find variable name @Unicorn Master Commented Feb 7, 2018 at 16:13
  • Can you elaborate on the error? Does it tell you which variable name it can't find?
    – ajthyng
    Commented Feb 7, 2018 at 23:21
1

Have you tried +this.state.name.

fetch('http://www.example.com/user-list.php?name='+this.state.text)
  //get status and append with data and return as one object
  .then(response =>  response.json())
  .then(responseobj => {
    this.setState({

     status:responseobj.msg,
   });

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.