DEV Community

loading...

Discussion on: Automate your getters and setters with Proxies

Collapse
aminnairi profile image
Amin Author • Edited

Hi Nahid and thanks for your comment!

Unfortunately, I haven't experienced enough with React to find something that could be useful. By creating this article, I was thinking more about use-cases related to the inner logic of your application, rather than something bound to a framework in specific.

But since React can be used with classes, you could make your own component class, for instance FetchableComponent to reuse api calls for instance (yeah I know, I'm giving the answer, it's too tempting).

import React from "react";
import ReactDOM from "react-dom";

class FetchableComponent extends React.Component {
    constructor() {
        super();

        return new Proxy(this, {
            get(target, property) {
                if (property === "api") {
                    return endpoint =>
                        fetch(
                            `https://jsonplaceholder.typicode.com/${endpoint}`
                        ).then(response => {
                            if (response.ok) {
                                return response.json();
                            }

                            throw new Error("unable to fetch the api");
                        });
                }

                return target[property];
            }
        });
    }
}

class UsersList extends FetchableComponent {
    constructor() {
        super();

        this.state = {
            users: []
        };
    }

    componentDidMount() {
        this.api("users").then(users => {
            this.setState({users});
        });
    }

    render() {
        return (
            <div>
                <h1>Users</h1>
                <ul>
                    {this.state.users.map(({id, username}) => (
                        <li key={id}>{username}</li>
                    ))}
                </ul>
            </div>
        );
    }
}

ReactDOM.render(<UsersList />, document.getElementById("users"));

In this case, you could see FetchableComponent like some sort of Trait like in PHP. Except you cannot use multiple trait like in PHP in this case since it is an extend. But I think you get the idea.

I haven't done React for a while so pardon my mistakes if there are any. What is important is the idea behind Proxies and React. I hope that answer your question!