Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does the separation of responsibility design pattern not work correctly in ReactJs?

I’m developing a very simple component that is capable of adding new items to a list that is controlled by useState.

The name of my component is ListComponent, see the code below:

import React, { useState, useEffect } from 'react';

const ListComponent = () => {
    const [list, setList] = useState([
        { title: 'Item 1' },
        { title: 'Item 2' },
        { title: 'Item 3' }
    ]);

    const addNewItem = () => {
        const newList = [...list, { title: `Item ${list.length + 1}` }];
        setList(newList);
    }

    return(
        <div>
            <h2>List of Items:</h2>
            {list.map((item, index) => (
                <div key={index}>
                    <h3>{item.title}</h3>
                </div>
            ))}
            <button onClick={addNewItem}>Add new Item</button>
        </div>
    )
}

export default ListComponent;

As you can see, the component starts with a list of 3 items, and when clicking the "addNewItem" button, Javascript adds another item to the list, so that the user can view it in real time (thanks to useState).

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

However, let’s suppose that I wanted to abstract part of the logic of this component into a service called listService.js.

To do this, I created a new file inside the services folder called listService.js:

class ListService {
    constructor() {
        this.list = [
            { title: 'Item 1' },
            { title: 'Item 2' },
            { title: 'Item 3' }
        ];
    }

    getList(){
        return [...this.list];
    }

    addNewItem(){
        const newList = [...this.list, { title: `Item ${this.list.length + 1}` }];
        this.list = newList;
    }
}

export default ListService;

Finally, I needed to adapt the logic of my ListComponent component as follows:

import React, { useState, useEffect } from 'react';
import ListService from '../../services/listService';

const ListComponent = () => {
    const [list, setList] = useState([]);
    const listService = new ListService();

    useEffect(() => {
        loadList();
    }, []);

    const loadList = () => {
        setList(listService.getList());
    }

    const addNewItem = () => {
        listService.addNewItem();
        loadList();
    }

    return(
        <div>
            <h2>List of Items:</h2>
            {list.map((item, index) => (
                <div key={index}>
                    <h3>{item.title}</h3>
                </div>
            ))}
            <button onClick={addNewItem}>Add new Item</button>
        </div>
    )
}

export default ListComponent;

Initially this code can load the list of components perfectly and even add "Item 4".

The problem is that the next time the user clicks the "addNewItem" button no item is added, as ReactJS always overwrites "Item 4".

enter image description here

I would like to know why ReactJS is not updating the list.

Are there things and design patterns (like separation of responsibility) that ReactJS can’t support?

>Solution :

That has nothing to do with SOLID.

Everytime react renders a component the function is executed including all code in it.
So when you call setList a new ListService will be instantiated.

Either replace list service with const listService = useMemo(() => new ListService(), []) or like mentioned in comments load the list using useEffect and manage state in component from now on.

const [list, setList] = useState([]);

useEffect(() => {
  setList(new ListService().getList());
}, []);

But because ListService.getList is not async we can also just do:


const [list, setList] = useState(new ListService.getList())

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading