Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

107
Visualizações
React Calling function from another file and useEffect

Hello I am trying to render the updated stuff from the database whenever the update is invoked to the database. I found this solution but right now my "add" method is not in the same file as the "fetch" method like in the linked question. I tried the below but it still isn't working:

file 1: (the return method will render the UploadedImages by mapping them)

const [UploadedImages,setUploadedImages] = useState([])

const fetchUserAllPhotos = async () => {
    const res = await client.get('/get-photos')
        setUploadedImages(res.data.photoList)
    } 

useEffect(()=>{
        
    fetchUserAllPhotos()
},[])

file 2:

import {fetchUserAllPhotos} from './Gallery/AllPhotos';
const addNewPhoto = async () => {
        if (success) {
            await fetchUserAllPhotos()
        }
}

However inside the file 1's return (render) method it is not giving the updated result whenever a new photos is added (I need to sign out and sign back in in order to see the change). How can I go about solving it?

what if the function is wrapped inside another one?

export default function PhotoGrid(props){
    const [UploadedImages,setUploadedImages] = useState([])
    
    const fetchUserAllPhotos = async () => {
        const res = await client.get('/get-photos')
            setUploadedImages(res.data.photoList)
        } 
    
    useEffect(()=>{
            
        fetchUserAllPhotos()
    },[])

}
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

you need to add this line at the bottom of file1

export {fetchUserAllPhotos}

In general, every time you want to import function, array, object etc it should look like this:

file1:

const func = () => {
  //implementaion of the function
}

export {func}

file2:

import {func} from './file1' //you need to give the path of file1


func() //now you can use the fanction everywhere in file2

note: you can export as many functions as you wants just be careful it important to use the same name in the export and in the import

export {func1, func2, func3, obj1, abj2, arr1, arr2}

if you are exporting function from react component you need to define the function outside the component

const func = () => {

}

export default function MyReactComponent(prop) {
//implementation of your component
}

export {func}

If you need to use prop of your component inside the function you can pass this prop as a function parameter.

I recomend to avoid from exporting function from react component because when your project becomes bigger it will start to be frustrate to find were you impliment each fanction. instead it is a best practice to add a new js file that you implement there all the fetches function, I usually call this file api.js This file should look something like this (I took this code from my project there I used axios to make the fetches to the server):

import axios from "axios"

const url = 'http://localhost:8080'

const api = {
getQuestions : async () => {
   return axios.get(`${url}/question/all`)
 },
getQuestionById : async (id) => {
   return axios.get(`${url}/question/${id}`)
 }
}

export default api;
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda