When attempting to store data in localstorage using React Hooks useState, an error occurs regarding mapping the array, resulting in a rendering issue where everything appears inverted. This

import React, { useState, useEffect } from 'react';
        import {
            FormControl,
            Form,
            Button,
            Container,
            Card,
            Row,
            Col,
        } from 'react-bootstrap';
        import { nanoid } from 'nanoid';
        import axios from 'axios';
        import * as usertz from 'user-timezone';
        import './card.css';
        import slp from '../assets/SLP.png';
        import ronin from '../assets/ronin.png';
        
        const AxieAPI = () => {
            const [toggle, setToggle] = useState(false);
            // Declare state variables
            // Code removed for brevity
    
        useEffect(() => {
            // Fetch data from API and local storage
            // Code removed for brevity
        }, [dataAll]);
    
        // Event handler to onChange event
        // Code removed for brevity
    
        // Event handler to onSubmit event
        // Code removed for brevity
        
        return (
            <div>
                <Container className="p-4">
                    <Button onClick={() => setToggle(!toggle)} className="mb-5">
                        Add Scholar
                    </Button>
                    {toggle && (
                        <Form onSubmit={onSubmitHandler}>
                            <Row className="mb-3">
                                // Form fields for input
                            </Row>
                            
                            <div className="d-grid gap-2 pt-3">
                                <Button type="submit" size="lg">
                                    Add User
                                </Button>
                            </div>
                        </Form>
                    )}
                    
                    <Container>
                        <Row>
                            {dataAll.slice(2).map((singleData) => {
                                // Mapping each user data 
                            })}
                        </Row>
                    </Container>
                </Container>
            </div>
        );
    };

export default AxieAPI;

The first time I took on the challenge of coding localStorage, but it seems like my code is upside down. Can someone help correct this? The array mapping seems off because I'm getting an error that says "Cannot read properties of null."

I encountered another problem where when I run npm start, it does not record the initial data into the State, resulting in null which leads to the error in array mapping.

I have been trying to tweak the localStorage save data and retrieve it, but every time I refresh, the data seems to get wiped out. I believe there might be a code error in the useEffect and Submit functions for storing the data, and every time I have to save empty data into the localStorage to prevent the error in mapping the array.

Answer №1

import React, { useState, useEffect } from 'react';
    {
        Form,
        Container,
        Card,
        Row,
        Col,
    }
from 'react-bootstrap';
import { nanoid } from 'nanoid';
import axios from 'axios';
import * as usertz from 'user-timezone';
import './card.css';
import slp from '../assets/SLP.png';
import ronin from '../assets/ronin.png';
import useLocalStorage from './hooks/useLocalStorage';

const AxieAPI = () => {
    const [toggle, setToggle] = useState(false);
    const [price, setPrice] = useState([{ current_price: '' }]);
    const [addFormData, setAddFormData] = useState({
        myName: '',
        roninAddress: '',
        manager: '',
        scholar: '',
    });

    const [dataAll, setDataAll] = useLocalStorage('localData', [
        {
            id: '',
            myName: '',
            roninAddress: '',
            manager: '',
            scholar: '',
            data: {
                slp: {
                    total: '',
                    claimableTotal: '',
                    lastClaimedItemA: '',
                    todaySoFar: '',
                    yesterdaySLP: '',
                },
                leaderboard: {
                    winRate: '',
                    winTotal: '',
                    drawTotal: '',
                    loseTotal: '',
                    elo: '',
                    rank: '',
                    name: '',
                },
            },
        },
    ]);

    const baseURL =
        'https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&ids=smooth-love-potion&order=market_cap_desc&per_page=100&page=1&sparkline=false';

    useEffect(() => {
        async function fetchData() {
            await axios.get(baseURL).then((response) => {
                // eslint-disable-next-line
                response.data.map((pri) => {
                    const answer = pri.current_price;
                    setPrice(answer);
                });
            });
            localStorage.setItem('localData', JSON.stringify(dataAll));
        }
        fetchData();
        // eslint-disable-next-line
    }, [dataAll]);

    const userAddress = addFormData.roninAddress.slice(6);

    var options = {
        method: 'GET',
        url: `https://axie-infinity.p.rapidapi.com/get-update/0x${userAddress}`,
        params: { id: `0x${userAddress}` },
        headers: {
            'x-rapidapi-host': process.env.REACT_APP_HOST,
            'x-rapidapi-key': process.env.REACT_APP_KEY,
        },
    };

    const onChangeHandler = async (e) => {
        // setRoninAddress(e.target.value);
        await e.preventDefault();
        try {
            const fieldName = e.target.getAttribute('name');
            const fieldValue = e.target.value;
            const newFormData = { ...addFormData };
            newFormData[fieldName] = fieldValue;
            setAddFormData(newFormData);
        } catch (error) {
            console.log(error);
        }
    };

    const onSubmitHandler = async (e) => {
        await e.preventDefault();

        await axios
            .request(options)
            .then(function (response) {
                const newUser = {
                    id: nanoid(),
                    myName: addFormData.myName,
                    roninAddress: addFormData.roninAddress,
                    manager: addFormData.manager,
                    scholar: addFormData.scholar,
                    data: response.data,
                };
                const newUsers = [...dataAll, newUser];
                setDataAll(newUsers);
                localStorage.setItem('localData', JSON.stringify(dataAll));
            })
            .catch(function (error) {
                console.error(error);
            });
        // localStorage.setItem('localData', JSON.stringify(dataAll));

        e.target.reset();
    };

    return (
        <div>
        ...
        </Container>
        </Container>
        </div>;
};

export default AxieAPI;

Resolved the issue using localStorage. Feel free to check it out if you face similar challenges.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Refreshing a webpage to accurately display changes made in a CRUD application without the need for a hard reset

My to-do app is almost fully functional - I can create items, mark them as completed, and delete them using a delete button. However, there's one issue: when I delete an item, the page doesn't update in real-time. I have to manually refresh the p ...

What are the best ways to implement advanced data filtering in JavaScript?

Is there a way to improve the filtering of data in the ngx-datatable? Currently, I have a filter that only works for the "Name" column. How can I adjust it to filter data from other columns like "id" or "phone" as well? filt ...

Utilizing async/await functionality within a React-Native component

I'm currently working on implementing a feature that authenticates users before rendering the main 'App' component. However, I'm facing an issue where my code is executing before the promise is resolved. class App extends Component { ...

JavaScript: abbreviated way to selectively append an element to an array

Currently, I am in the process of creating a Mocha test for a server at my workplace. When dealing with customer information, I receive two potential phone numbers, with at least one being defined. var homePhone = result.homePhone; var altPhone = ...

Two consecutive instances of the outcome recorded in the ajax table

I am trying to add data to a table, but one of my results is appearing twice. Here is the JSON response I received: groupname […] 0 {…} survey_id 2 group_name DEMO 1 {…} survey_id 1 group_name TEST This is what my AJAX success function ...

Text input in Bootstrap not reaching full width

Trying to achieve a Bootstrap textfield embedded in a panel that spans 100% of the remaining space-width within the panel. However, this is the result obtained: The blue border represents the edge of the panel. Below is the code being used: <div clas ...

Replacing a string using Regular Expression based on certain conditions

When working with a node.js server, I encountered the need to modify URL addresses using JavaScript in a specific way: For instance: hostX/blah/dir1/name/id.js?a=b --> name.hostY/dir2.js?guid=id&a=b Another example: hostZ/dir1/name/id.js --> ...

What is the process for creating a linked TreeNode in the Ant tree design?

After completing a tree design utilizing Ant Design, I encountered an issue where certain nodes within the tree needed to act as links. Despite my attempts to directly assign links, they were not functioning properly. array.map((node) => { if(node.t ...

Transferring information submitted in a form to a service using AngularJS

Trying to implement a shopping cart app where I need to pass an object into a service function using Angular. Following advice from another post, but encountering an unprovided error and a strange syntax error on page load. The issues seem to be originatin ...

Encountering 'undefined' issue with find operation in mongoDB

Seeking assistance to utilize all available values in my code. bericht.find({ room: room }).toArray(function(err, docs) { assert.equal(err, null); str2 = str2 + docs.message; The function I'm using can successfully loca ...

Discovering the distinction between arrays of JQuery objects

I have a task that requires the following steps: var elems = $('.lots-of-elements') Next, I need to make an AJAX request and then do this: var moreElems = $('.lots-of-elements') Finally, I am looking to identify only the new element ...

Why isn't my List<string> being retrieved from the MVC Controller in an $ajax request?

I am attempting to generate customized lists in my cshtml file through an ajax request. .ajax({ type: "GET", cache: false, url: "@Url.Action("getValidationLists")", contentType: "application/json", dataType: "json", ...

Hide the div element when the url contains the word 'word'

I did some research online, but I couldn't find any information on whether this is doable. I'm currently using IPBoard and after their latest IPS4 update, I'm facing an issue where I can't simply change the homepage anymore. Now, I have ...

Deployment to Amazon Amplify encounters failure when using Next JS

I've been encountering continuous failures while trying to deploy an SSG app on Next JS. The build consistently fails, and I'm met with an error message. Despite following the deployment documentation for SSG sites on Amazon diligently, the error ...

What could be the reason for my directive not properly interpolating the scope variable?

I attempted to create a directive that would swap out a CSS link with an inline style definition. Check out the functional version here. Now, I am hoping to achieve the same functionality using interpolation, so that I don't have to manually set the ...

Error: An attempt to make changes to a database that does not permit mutations has resulted in an InvalidStateError

I am facing an issue while attempting to initiate a transaction within the then() function. An exception is thrown when I try to do so. Below is the code snippet in question: open.onsuccess = function (e1) { var dbase = e1.target.result; $.get("https://w ...

Guide on displaying the appropriate component in NextJs routes

Whenever I switch routes, I encounter an issue. While navigating between pages works fine, dynamic routes are not rendered correctly. In the routes, I have a folder called uw with a file named [table].js inside. For example, when I manually navigate to uw ...

npm not working to install packages from the package.json file in the project

When using my macbook air, I encounter an issue where I can only install npm packages globally with sudo. If I try to install a local package without the -g flag in a specific directory, it results in errors. npm ERR! Error: EACCES, open '/Users/mma ...

There seems to be an issue with the Alexa skill's ability to provide a response after another

I am currently developing an Alexa skill that involves a multi-step dialog where the user needs to respond to several questions one after the other. To begin, I am trying to kick things off by implementing a single slot prompt. I am checking if the slot is ...

In strict mode, duplicate data properties are not allowed in object literals when using grunt-connect-proxy

I recently started following a tutorial on AngularJS titled "Hands on Angularjs" by Tutsplus. In the tutorial, the instructor uses the grunt-connect-proxy package to redirect ajax requests to a Rails server running on localhost:3000. However, I believe the ...