how to save the data from firebase I recently Created with axios and react?

Viewed 169

I am kinda new into react and web dev overall, I want to ask, where is the issue in my proble? I created a database with firebase, posting into it went fine, but now I am trying to GET the date I posted before and store it Into a variable, so then I can iterate through the data and map different components for each data. I am using axios, here is the code:

function CreateBlog(props) {
   const [fetchedData, setFetchedData] = useState();
    useEffect(() => {
          axios.get("https://diary-page-default-rtdb.firebaseio.com/diaryPages.json")
        .then((response) => {
            console.log(response.data);
            setFetchedData(response.data);
            console.log(fetchedData)
        })
        .catch(error => console.log("error occured:", error))
    }, []);

so as I console.log the response.data I get the object with the data stored in the database, but when I setFetchData and console.log the fechedData I get undefined. Is there any simple way to store the data inside "fetchedData" as an array where every different object represents a part of the array so that later on I can map through the array and display the data in separate components?

1 Answers

You are storing the data correctly, but you are not able to console.log them straight away because the useState operates asynchronously.

If you want to console.log your fetchedData, have a useEffect listening to changes on that state (for demonstration purposes):

useEffect(() => {
  console.log(fetchedData)
}, [fetchedData]);

A further suggestion I would give (not essential though), is to set your initial state as an empty array since that's the type of data you are storing:

const [fetchedData, setFetchedData] = useState([]);

From here, you can map through your data as such:

{fetchedData?.map((data, index) => <div key={index}>{data}</div>}

Just make sure data is not an object if you copy my example, or it will return you an error since you can't display objects inside jsx

Related