Dictionary Not Saving/Updating - useState

Viewed 13

Apologies if this question has an easy answer, but it seems that the dictionary won't save with useState by creating a copy of it, but the dictionary does update as I see it print through the console.

Logic (ItemViewedCounter.js):

import { useState } from 'react';

var HashMap = require('hashmap'); // https://www.npmjs.com/package/hashmap

var itemMap = new HashMap();
var mostViewedItems = {}; // dictionary for easier access
var maxVal = 0;
var minVal = 0;
var maxItem;
var minItem;
const maxMostViewed = 6; // number of total most viwed items


const ItemViewedCounter = () => {
    const [mostViewedItemsOutput, updateMostViewedItems] = useState({});

    const updateDictionary = (itemName, link, info) =>{
        const itemObject = { title: itemName, link: link, info: info};
        
        /* Logic to update dictionary goes here.
        to make things simple we'll update with parameters*/
        mostViewedItems[itemName] = itemObject;

        console.log("UPDATING DICTIONARY!!! Size:" + Object.keys(mostViewedItems).length);
        console.log(mostViewedItems);
        updateMostViewedItems(mostViewedItems);
        console.log(mostViewedItemsOutput); //<--it won't update even after delay
    }

    return {updateDictionary, mostViewedItemsOutput};
}

export default ItemViewedCounter;

UI (MostViewed.js):

import Container from 'react-bootstrap/Container';
import Row from 'react-bootstrap/Row';
import Col from 'react-bootstrap/Col';
import ItemPlacecard from './ItemPlacecard';
import ItemViewedCounter from '../Logic/ItemViewedCounter';
import React from 'react';

const MostViewed = () =>{
    const {mostViewedItemsOutput} = ItemViewedCounter();

    const boarder = {
        border: 'solid',
        borderRadius: 12,
        marginRight: '0rem',
        marginLeft: '5rem',
        marginTop: '2rem',
        marginBottom: '2rem',
        maxWidth: 'calc(100% - 10rem)'
    }

    const spacing={
        marginRight: '0rem',
        marginLeft: '5rem',
        marginTop: '1rem',
        marginBottom: '0rem',
    }

    const columns = 3;
    return(
        <>
        <h1 style={spacing}>Most Viewed</h1>
        <Container style={boarder}>
            <Row xs={columns}>
                {Object.entries(mostViewedItemsOutput).map(([key,value], aKey)=>{
                    const item = value;
                    return(<React.Fragment key={aKey}>
                        <Col>
                            <ItemPlacecard title={item.title} link={item.link} info={item.info}/>
                        </Col>
                    </React.Fragment>);
                })}
            </Row>
        </Container>
        </>
    );
}

export default MostViewed;

One thing to note is that the updateDictionary() method is called in a different component as an onClick() event

0 Answers
Related