How to call a Function from another file, within a Function from the main file?

Asked

Viewed 729 times

1

I have in the file App.js And the first time it’s loaded, it calls the const response = await api.get('/searchDate');, and returns a list of dates. I want to take the first position on the list, call the file Transaction js. and search on the back, the information according to the date[0].

I could do this?

Observing: Every time a new date the file is selected Transaction js. is called and sends the dateSelected and searches the information. With the call on html in the return <Transaction dateSelected={dateSelected} />.

However, I wanted to call it the first time it loads the page, with the first date of the list.

App.js file

function App() {
  const [dates, setDates] = useState([]);
  const [dateSelected, setDateSelected] = useState();

  useEffect(() => {
    async function loadDates(){
      const response = await api.get('/searchDate');
      setDates(response.data.yearMonth);
    };
    console.log(dates[0]); // aqui ele mostra certinho o date da primeira posição - ele seria o dateSelected
    // Como chamar o function Transaction({dateSelected}) {
    loadDates();
  },[dates[0]]);

  const handleChange = (event) => {
    setDateSelected(event.target.value);
  };
  return (
    <div id="app">
      <main>
        <Transaction dateSelected={dateSelected} />
      </main>
    </div>
  );
}

Arquivo Transaction.js

function Transaction({dateSelected}) {
  const [transactions, setTransactions] = useState([]);
  useEffect(() => {
    async function loadTransaction() {
      const response = await api.get('/search?yearMonth='+dateSelected);
      setTransactions(response.data.transaction);
    };
    loadTransaction();
  }, [dateSelected]);
  • the component needs a state and that state controls whether it is loaded 1 or more times! only this I think is necessary, now is changing is because you in the same code changes the state or maybe catches a state that is changing and so the file loading.

1 answer

1


Fix a demo on Codesandbox which certainly does not match the functionality you want, but exemplifies how to import files and extract Hooks. For code reuse, use import. You typically import functions, classes or constants.

import React, { useState, useEffect } from "react";
import api from "../utils/fakeApi";
import Transaction from "./Transaction";

For life cycle reuse, create custom Hooks. By convention, a hook should start with use and have a name that starts with a capital letter right after.

import { useState, useEffect } from "react";
import api from "../utils/fakeApi";

export default function useTransaction(dateSelected) {
  const [transactions, setTransactions] = useState([]);

  useEffect(() => {
    async function loadTransaction() {
      const response = await api.get("/search?yearMonth=" + dateSelected);
      setTransactions(response.data.transaction);
    }
    loadTransaction();
  }, [dateSelected]);

  return transactions;
}

Do not confuse Hooks with UI components. These return components and may (or may not) use Hooks. Functions or UI classes must start with uppercase.

import React from "react";
import useTransaction from "../hooks/useTransaction";

export default function Transaction({ dateSelected }) {
  const transactions = useTransaction(dateSelected);

  return (
    <div>
      <h2>transactions</h2>

      <p>para {dateSelected.toDateString()}:</p>

      <ul>
        {transactions.map(item => (
          <li key={item}>{item}</li>
        ))}
      </ul>
    </div>
  );
}
  • I understood what you did. There’s only one thing I need. In the code you start with the const [dateSelected, setDateSelected] = useState(new Date()); However, I cannot start with new Date(), I need to start with the first Date that comes from the call of const response = await api.get("/searchDate");. How would you do that?

  • Apis have combinations of states: loading vs not-loading and success vs error; you must deal with the 4 possibilities. Enrich your hook to return all this. Ex: https://andrewstevens.dev/posts/useApi-react-hook/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.