0

I have the following react js code page:

import React, { useState } from "react";
import { Auth, API } from "aws-amplify";

function dailyFiles(props) {
 const [apiError502, setApiError502] = useState(false); 

  // Pull out into a generic reusable function
  const getData = async () => {
    try {
      let apiName = "Dev";
      let path = "/test";
      let myInit = {
        headers: {
          Authorization: `Bearer ${(await Auth.currentSession())
            .getIdToken()
            .getJwtToken()}`
        }
      };
       var result = await API.get(apiName, path, myInit);
    } catch (e) {
      if (e.message === "Request failed with status code 502") {
        toggleApiError502(true);
      } else {
        alert(JSON.stringify(e));
        props.onLogout();
      }
    }
    return result;
  };

  const toggleApiError502 = (show = false) => {
    setApiError502(show);
  };

  var files = {
    Files: [
      {
        Day: "Monday",
        file: "10-02-2020"
      },
      {
        Day: "Friday",
        file: "14-02-2020"
      }
    ]
  };

  return (
    <div className="animated fadeIn">
      <div>
        {files.Files.map(block => block.Day + ": " + block.file + "  ")}
      </div>
    </div>
  );
}

export default dailyFiles;

When I call from my div the static Var files variable:

var files = {Files: [{Day: "Monday",file: "10-02-2020"},{Day: "Friday",file: "14-02-2020"}]};

  <div>
    {files.Files.map(block => block.Day + ": " + block.file + "  ")}
  </div>

I got the expected result, but how can I get the same result calling my function getData()?

const getData = async () => {

getData function call an API which return the same content result as var files has?

I've tried to call the function with this.getdata() within the div but not successful result.

2 Answers 2

1

Use useEffect to get the data after the component has mounted.

function dailyFiles(props) {
  const [apiError502, setApiError502] = useState(false);
  const [files, setFiles] = useState([]);

  useEffect(() => {
    // Pull out into a generic reusable function
    const getData = async () => {
      try {
        let apiName = "Dev";
        let path = "/test";
        let myInit = {
          headers: {
            Authorization: `Bearer ${(await Auth.currentSession())
              .getIdToken()
              .getJwtToken()}`
          }
        };
        var result = await API.get(apiName, path, myInit);
        setFiles(result); // set your files here
      } catch (e) {
        if (e.message === "Request failed with status code 502") {
          setApiError502(true);
        } else {
          alert(JSON.stringify(e));
          props.onLogout();
        }
      }
      return result;
    };
    // call getData
    getData();
  }, []);

  return (
    <div className="animated fadeIn">
      <div>
        {Array.isArray(files.Files) && files.Files.map(block => block.Day + ": " + block.file + "  ")}
      </div>
    </div>
  );
}

export default dailyFiles;
Sign up to request clarification or add additional context in comments.

4 Comments

Works great!! I never thought even to use useEffect. Thanks!!
What about if my json has more than one level. Would be possible to work with a nested array?
When I change my Json to a complex json (more than one level) it doesn't work. I'm trying to understand why you use Array.isArray(files.Files) && which based on the documentation is for validate an array object. When I remove this part of the code it doesn't work. Could you explain a bit? Sorry for so many question I really new with this stuff.
yes it checks if files.Files is array, if it's not it won't continue to render the items.
0
  1. You're using a functional component so if you want to call the getData function you should just use getData().

  2. Anyway, since getData() is asynchronous you should make few changes regarding how you use that inside the render function. For example, you can initially take a variable that has an empty array and once you get the data from the backend inside getData you can reassign that variable with the response data.

Actually you might want to call getData when your component loads for the first time so you can use Hooks for that. There are several other ways it all comes down to your preference.

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.