3

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.

3
  • 1
    Can't reassign a const. const resObj = {}; should be let resObj = {}; Commented May 27, 2020 at 22:08
  • 1
    Does this answer your question? Const in JavaScript: when to use it and is it necessary? Commented May 27, 2020 at 22:08
  • @Nick I have tried it and it doesn't work for some reason... error: " There was an error with your request" message: "respObj is not defined" Commented May 27, 2020 at 22:24

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

3 Comments

I still get error: " There was an error with your request" message: "respObj is not defined"
mmmm... It look like a different problem. Wait, I think you just misspelled resObj with respObj
Yes, thank you guys, you are legends! Such a silly mistake and I have been staring at the screen for 2 days, trying to solve it... I have changed the CONST to LET and fixed the typo and it all works now perfectly, thank you ! Thank you @Luca Fabbian !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.