0

I am using Expo of React Native which i need to save the API Fetch response to state.

My code is like this:

onPress={async () => {

                  if (this.camera) {
                    const options = { quality:0, base64: true};
                    let photo = await this.camera.takePictureAsync(options);
                      setTimeout(()=>{     
                      fetch('https://c7pl8gkrj6.execute-api.ap-southeast-1.amazonaws.com/prod/rekog', {
                        method: 'POST',
                        headers: {
                          Accept: 'application/json',
                          'Content-Type': 'application/json',
                        },
                        body: JSON.stringify({
                          base64: photo['base64'],
                        }),
                      }).then((responseJson) => {  
                        this.setState({
                            response:responseJson
                            })
                        })
                        .catch((error) => {
                          console.error(error);
                        });
                        this.setState({captured:true})
                        }, 3000)

                  }
                }}

I want to store the response in the state variable named 'response'. But When I want to display the response saved in state, it will render null.

if(this.state.captured){
        console.log(this.state.response)
        return(
          <View style={styles.container}>
        <SectionList
          sections={[
            {title: 'response1', data: [this.state.response]}
          ]}
          renderItem={({item}) => <Text style={styles.item}>{item}</Text>}
          renderSectionHeader={({section}) => <Text style={styles.sectionHeader}>{section.title}</Text>}
          keyExtractor={(item, index) => index}
        />
      </View>
        );
         }else{
           ...

Here, console.log(this.state.response) shows {} i.e null value. Is it the problem of async function which is not displaying the value saved in state.

2 Answers 2

0

No definitely not, as long as your API does return a result, but you should do this.

onPress={async () => {

              if (this.camera) {
                const options = { quality:0, base64: true};
                let photo = await this.camera.takePictureAsync(options);
                  setTimeout(()=>{     
                  await fetch('https://c7pl8gkrj6.execute-api.ap-southeast-1.amazonaws.com/prod/rekog', {
                    method: 'POST',
                    headers: {
                      Accept: 'application/json',
                      'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                      base64: photo['base64'],
                    }),
                  }).then(function(response) {
                      return response.json()
                    }).then((responseJson) => {  
                    this.setState({
                        response:responseJson
                        })
                    })
                    .catch((error) => {
                      console.error(error);
                    });
                    this.setState({captured:true})
                    }, 3000)

              }
            }}

You missed a few lines there.

Sign up to request clarification or add additional context in comments.

Comments

0

You need to extract the response firstly so you have to write one then before your setState then promise like below where reponse.json() extract the actual response and pass it to the responseJson. Thanks, hope it will usefull for you.

   .then(reponse => response.json())
   .then((responseJson) => {  
       this.setState({
           response:responseJson
       })
    })

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.