Home > Blockchain >  React Calling function from another file and useEffect
React Calling function from another file and useEffect

Time:03-26

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?

CodePudding user response:

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}
  • Related