1

I'm trying to fetch data from an API(I created my own Rest API using JSON-server). But I'm unable to fetch anything. however, I'm able to see the data when I navigate to localhost:3000/events. There's no other error in my app. I only get this when I run the app it says network request failed. All the components are working fine. Just not getting the data. I've tried some other online APIs still not getting any response. I've tried with async/await. I'm using the app with IOS but have tried with Andriod as well. Same problem occurs. Attaching the code snippets. Any help would be highly appreciated. Thanks

Created the getEvent Function:

const { manifest } = Constants;
const api = manifest.packagerOpts.dev
  ? manifest.debuggerHost.split(`:`).shift().concat(`:3000`)
  : `api.example.com`;

const url = `http://${api}/events`;

export function getEvents() {
  return fetch(url)
  .then(response => response.json())
  .then(events => events.map(e => ({ ...e, date: new Date(e.date) })))
}

Using it inside the componentDidMount

componentDidMount() {
    // getEvents().then(events => this.setState({ events }));

    setInterval(() => {
      this.setState({
        events: this.state.events.map(evt => ({
          ...evt,
          timer: Date.now()
        }))
      });
    }, 1000);

    this.props.navigation.addListener("didFocus", () => {
      getEvents().then(events => this.setState({ events }));
    });
  }

Data that I'm trying to fetch.

{
  "events": [
    {
      "title": "Demo a new app",
      "date": "2020-03-29T13:45:18.000Z",
      "id": "001c9b6d-00a9-465c-a2d3-afb7176a0a87"
    }
  ]
}
5
  • You will get "Network request failed" when your server is not working or internet connection is not available. so please check and try again with the same code. Print the log in the debugger and check. Commented Feb 19, 2020 at 13:24
  • I had huge problems while conneting to my own REST API because my url was wrong check that too. Commented Feb 19, 2020 at 13:36
  • Can you show your code with API in expo snack ? , How could help then Commented Feb 19, 2020 at 13:44
  • @AnujSharma Hi Anuj, I'm new to React Native not familiar to expo snack, Do you just want me to upload the project on expo snack and share the link with you? How are you going to use the Rest API that I'm running locally? Thanks Commented Feb 19, 2020 at 14:59
  • Yes , but if you are using API locally then i will not able to check your API , but when i was new to react i use alerts to check data flow . You also can do that by setting alerts on various stages like first of all print your data that you are passing to API use alert(JSON.stringify(data)); and then check weather you are passing right data to API or not. This helps you a lot, and let me know if it will not help you. Commented Feb 19, 2020 at 18:07

1 Answer 1

1

you can use axios as of fetch , it is also used to hit API's and get response from them , and it is simple and easy way as compare to fetch.

run npm i react-native-axios on your project root floder to install the library and import it and use it , here is an example of axios , in which the user will login to screen and will hit the login API , the user enter their credentials and if they are correct as in API then user will get response or user will login successfully.

    import axios from "axios";
export default class Login extends Component {
  constructor(props) {
    super(props);
    this.state = {
      email: "",
      password: "",
      }
  };

  onPresssighnin = () => {
      var data = {
       //parameters to pass API
        Email: this.state.email,
        Password: this.state.password,
      };
      axios
        .post(" insert API url here", data, {
          "Content-Type": "application/json"
        })
        .then(
          response => {
           //get response here
            alert(JSON.stringify(response))
                      },
          error => {
            //get errormessage here
            errormessage = error.Message;
            alert(errormessage);
          }
        );
    }
  };
  render() {
      return (
              <View style={styles.logoContainer}>                
             <Input
                    borderless
                    placeholder="Email"
                    onChangeText={email => this.setState({ email })}
                    iconContent={
                      <Icon
                        size={16}
                        color={ditsTheme.COLORS.ICON}
                        name="ic_mail_24px"
                        family="DitsExtra"
                        style={styles.inputIcons}
                      />
                    }
                  />
                  <Input
                    password
                    borderless
                    placeholder="Password"
                    onChangeText={password =>this.setState({ password })}
                    iconContent={
                      <Icon
                        size={16}
                        color={ditsTheme.COLORS.ICON}
                        name="padlock-unlocked"
                        family="DitsExtra"
                        style={styles.inputIcons}
                      />
                    }
                  />

                    <Button
                      color="primary"
                      style={styles.createButton}
                      onPress={this.onPresssighnin} >
                      <Text bold size={14} color={ditsTheme.COLORS.WHITE}>
                        SIGN IN
                      </Text>
                    </Button>  
              </View>
      )
    }
  }
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: 'rgb(32, 53, 70)',
    flexDirection: 'column',
  },
    buttonText: {
    textAlign: 'center',
    color: 'rgb(32, 53, 70)',
    fontWeight: 'bold',
    fontSize: 18
  }
})

Feel free for Doubts.

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

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.