Denis Denchev
Denis Denchev

Reputation: 81

Error "Assignment to constant variable" in ReactJS

I did follow a tutorial of how to integrate mailchimp with node backend. I have never touched back end, so am pretty lame at it. When I POST to their API I get the subscriber's credentials, but I get an error back - "Assignment to constant variable". Reading through the web and other SO questions, it seems like I am trying to reassign a CONST value.

I had a goooooooooood look at my code and the only thing I have noticed that might be issues here is

request(options, (error, response, body) => {


    try {
            const resObj = {};
            if (response.statusCode == 200) {
                resObj = {
                    success: `Subscibed using ${email}`,
                    message: JSON.parse(response.body),
                };
            } else {
                resObj = {
                    error: ` Error trying to subscribe ${email}. Please, try again`,
                    message: JSON.parse(response.body),
                };
            }
            res.send(respObj);
        } catch (err) {
            const respErrorObj = {
                error: " There was an error with your request",
                message: err.message,
            };
            res.send(respErrorObj);
        }
    });

I have noticed I am creating an empty object called "resObj", then trying to assign a value to it. I have tried changing the CONST to LET, but I get an error saying: "resObj is not defined".

Here is my front end code:

 import React, { useState } from "react";
import "./App.css";
import Subscribe from "./components/Subscribe";
import Loading from "./components/Loading/Loading";
import axios from "axios";
import apiUrl from "./helpers/apiUrl";

function App() {
    const [loading, setLoading] = useState(false);
    const [email, setEmail] = useState("");

    const handleSendEmail = (e) => {
        setLoading(true);
        console.log(email);
        axios
            .post(`${apiUrl}/subscribe`, { email: email })
            .then((res) => {
                if (res.data.success) {
                    alert(`You have successfully subscribed!, ${res.data.success}`);
                    setEmail("");
                    setLoading(false);
                } else {
                    alert(`Unable to subscribe, ${res.data.error}`);
                    console.log(res);
                    setLoading(false);
                    setEmail("");
                }
            })
            .catch((err) => {
                setLoading(false);
                alert("Oops, something went wrong...");
                console.log(err);
                setEmail("");
            });
        e.preventDefault();
    };

    const handleInput = (event) => {
        setEmail(event.target.value);
    };

    // const handleLoadingState = (isLoading) => {
    //  setLoading({ isLoading: loading });
    //  console.log(loading);
    // };
    return (
        <div className='App'>
            <h1>Subscribe for offers and discounts</h1>

            {loading ? (
                <Loading message='Working on it...' />
            ) : (
                <Subscribe
                    buttonText='Subscribe'
                    value={email}
                    handleOnChange={handleInput}
                    handleOnSubmit={handleSendEmail}
                />
            )}
        </div>
    );
}

export default App;

And the Back end code:

const restify = require("restify");
const server = restify.createServer();
const corsMiddleware = require("restify-cors-middleware");
const request = require("request");
require("dotenv").config({ path: __dirname + "/variables.env" });

const subscribe = (req, res, next) => {
    const email = req.body.email;
    const dataCenter = process.env.DATA_CENTER;
    const apiKey = process.env.MAILCHIMP_API_KEY;
    const listID = process.env.LIST_ID;

    const options = {
        url: `https://${dataCenter}.api.mailchimp.com/3.0/lists/${listID}/members`,
        method: "POST",
        headers: {
            "content-type": "application/json",
            Authorization: `apikey ${apiKey}`,
        },
        body: JSON.stringify({ email_address: email, status: "subscribed" }),
    };

    request(options, (error, response, body) => {
        try {
            const resObj = {};
            if (response.statusCode == 200) {
                resObj = {
                    success: `Subscibed using ${email}`,
                    message: JSON.parse(response.body),
                };
            } else {
                resObj = {
                    error: ` Error trying to subscribe ${email}. Please, try again`,
                    message: JSON.parse(response.body),
                };
            }
            res.send(respObj);
        } catch (err) {
            const respErrorObj = {
                error: " There was an error with your request",
                message: err.message,
            };
            res.send(respErrorObj);
        }
    });
    next();
};

const cors = corsMiddleware({
    origins: ["http://localhost:3001"],
});

server.pre(cors.preflight);
server.use(restify.plugins.bodyParser());
server.use(cors.actual);
server.post("/subscribe", subscribe);

server.listen(8080, () => {
    console.log("%s listening at %s", server.name, server.url);
});

If anyone could help I would be very grateful. The subscription form works, but I need to clear that bug in order for my front end to work correctly onto submission of the form.

Upvotes: 3

Views: 26851

Answers (1)

Luca Fabbian
Luca Fabbian

Reputation: 215

Maybe what you are looking for is Object.assign(resObj, { whatyouwant: value} )

This way you do not reassign resObj reference (which cannot be reassigned since resObj is const), but just change its properties.

Reference at MDN website

Edit: moreover, instead of res.send(respObj) you should write res.send(resObj), it's just a typo

Upvotes: 4

Related Questions