Home > Net >  ReactJs Save function from other file to variable in Component
ReactJs Save function from other file to variable in Component

Time:11-29

I have this file apiService.js

import axios from "axios";

const url = "/getCrimesByCategory/AUTO_THEFT";

export function getAllCrimes() {
    axios.get(url).then(response => {
        console.log(response.data)
        return response;
    })
}

and this file: dataPage.js

import React, { Component } from 'react';
import { MDBDataTable } from 'mdbreact';
import '../App.css';
import { getAllCrimes } from '../controller/ApiService.js';

class DataPage extends Component {

  render() {

    str = getAllCrimes();
    console.log("this is str: "   str)
    return (
      <p>this is str: {str}</p>
    );
  }
}

export default DataPage;

the problem is that console.log("this is str: " getAllCrimes()) returns "this is str: undefined"

I need to return the response of the function to use it later in the dataPage react Component.

CodePudding user response:

There are a few issues here:

  1. You have return the data from the getAllCrimes function. You can fix this by just adding a return in front the API (axios) call.
  2. Even if returned, you won't get the data because API calls work in a different way. They work asynchronously. You won't get the data immediately(in your render method). But, you can use the advantage of state and lifecycle methods here to solve it.
class DataPage extends Component {
  state = {
    str: null, // or "", or {}, or [], based on your need.
  };

  componentDidMount() {
    getAllCrimes.then((crimes) => {
      this.setState({
        str: crimes,
      });
    });
  }

  render() {
    const { str } = this.state;
    console.log("this is str: "   str);
    return str ? <p>this is str: {str}</p> : <p>You gotta wait</p>;
  }
}

I have created a state for the component with str as null initially. I just let the component to render, and once it is rendered, the componetDidMount will execute. It calls the API(the function) and once the API returns some value, it will passed to the then. (learn Promises if not familiar). There, we update the state, which causes a re-render, but now str has the data.

  • Related