How to recursively add HTML elements from a JSON object?

I have a JSON object of an unknown size, number of keys, and depth level.
Example:

{
  "domains": [
    {
      "url_part": "domainOne.com",
      "children": [
        {
          "url_part": "one",
          "children": [
            {
              "url_part": "a",
              "children": [
                {
                  "url_part": "page1",
                  "children": []
                },
                {
                  "url_part": "page2",
                  "children": []
                }
              ]
            },
            {
              "url_part": "b",
              "children": []
            },
            {
              "url_part": "c",
              "children": []
            }
          ]
        },
        {
          "url_part": "two",
          "children": [
            {
              "url_part": "a",
              "children": [
                {
                  "url_part": "page1",
                  "children": []
                },
                {
                  "url_part": "page2",
                  "children": []
                }
              ]
            }
          ]
        }
      ]
    },
    {
      "url_part": "domainTwo.com",
      "children": []
    }
  ]
}

And I want to have a page initially just have a button for each domain, then when you click each button it expands one layer down:

domainOne.com

domainTwo.com

When you click on DomainOne.com turns into:

domainOne.com

–one

–two

domainTwo.com

enter image description here

I am able to create a button for each of the domains, but am only able to reach one level down when it comes to making buttons for the children.

I am passing in:

  • the parentJSON (domains[“domainone.com”] in the first call)
  • the treelevel (to keep track of indentation)
  • the currentURL (for naming and later uses)
  • the “aboveDiv”, the div in which all of the children are appended under

The function that I’m trying to use recursively looks like this:

function childrenButtons(parentJSON, level, currentURL, aboveDiv){
                if (parentJSON["children"] == "[]") {
                    //if the JSON you are passing in doesnt have children, this is the end
                    console.log("+++++++++no more kids to show++++++++++++");
                    return 0;
                }
                else {
                 
                    
                    for (let j = 0; j < parentJSON["children"].length; j++) {

                        button.addEventListener("click", function () {
                            ////for each child, create their own div
                            const childDivElement = document.createElement("div");
                            const domainDivElementID = "childDivElement" + j;
                            childDivElement.setAttribute("id", domainDivElementID);
                            aboveDiv.append(childDivElement);

                            //create and add button with name = full path of button
                            const button = document.createElement("button");
                            const currChild = domains[i]["children"][j]["url_part"];
                            fullURL = currentURL + "/" + currChild;
                            button.innerHTML = fullURL;
                            button.style.marginLeft = level*20;
                            childDivElement.append(button);

                            let newParentJSON = parentJSON["children"][j]
                            console.log(parentJSON["children"][j]);

                            treeLevel++;
                            return childrenButtons(newParentJSON, treeLevel, fullURL, childDivElement);

                        }, false);
                    }
                }
            }

UseField formik empty value

i’m trying to listen paste event in markdown window then show image at link from server. Like github issues. It’s work correct, but i stuck with problem field.value inside function is empty and i can’t work with this string, useEffect shows it with value. Link on img in end of code
[enter image description here][1]

const [field, meta, helpers] = useField(name)

  const pasteValue = (event) => {
    const items = (event.clipboardData || event.originalEvent.clipboardData)
      .items

    for (let index in items) {
      const item = items[index]
      if (item.kind === 'file') {
        const blob = item.getAsFile()
        const reader = new FileReader()

        reader.onload = async function (event) {
          const result = event.target.result
          // todo compress
          if (result) {
            const loadText = '...Uploading image'
            const name = `mem1-${Math.random()}`
            helpers.setValue(`![image](${loadText})`)
            console.log(field.value)

            await fetcher('/images', {
              method: 'POST',
              body: JSON.stringify({
                base64_image: result,
                image_name: name,
              }),
            }).then((res) => res?.image_url)

            console.log(field.value)
 
            // helpers.setValue(`![image](${url})`)
            // helpers.setValue(field.value.replace(loadText, `![image](${url})`))
          }
        }
        reader.readAsDataURL(blob)
      }
    }
  }

  console.log('Effect ', field.value) ```


  [1]: https://i.stack.imgur.com/B92rh.png

Javascript chaining window.onload functions

I have a javascript function that grabs a dataset numeric value and appends it to an XMLhttprequest parameter. It has to run onload as the content is printed dynamically through php.

I now am trying to create a simple carousel for the elements printed and finding some difficulty chaining onload functions.

I’ve found creating an additional onload event for anything breaks the first onload event. What can I do here?

function userData() {
  let infoWrap = document.querySelector(".agent-detail-info").dataset.id;
  console.log(infoWrap);
  return infoWrap;
}
window.onload = userData;

window.onload = () => {
  const request = new XMLHttpRequest();
  request.open(
    "GET",
    `url&usertolookup=${userData()}`
  );

  request.onload = function () {
    let response = request.response;
    let parsedData = JSON.parse(response);
    console.log(parsedData);

    let testimonials = parsedData.data.testimonials.details;

    testimonials.forEach((testimonial, index) => {
      const testimonialWrap = document.querySelector(".testimonials");
      // Create testimonials container
      let innerTestimonials = document.createElement("div");
      innerTestimonials.className = "inner-testimonial-container";
      testimonialWrap.appendChild(innerTestimonials);

      // Create star rating container
      let starWrap = document.createElement("div");
      starWrap.className = "testimonial-stars";
      innerTestimonials.appendChild(starWrap);

      // Create Testimonial Content
      let innerTestimonialParagraph = document.createElement("p");
      innerTestimonials.appendChild(innerTestimonialParagraph);

      // Create Testimonial Signature
      let innerTestimonialSignature = document.createElement("address");
      innerTestimonials.appendChild(innerTestimonialSignature);

      // Loop through rating value and create elements
      let rating = testimonial.rating;
      for (let i = 0; i < rating; i++) {
        let star = document.createElement("i");
        star.className = "fa fa-star";
        starWrap.appendChild(star);
      }

      // Insert Testimonial Content
      let testimonialText = testimonial.Testimonial;
      innerTestimonialParagraph.innerHTML = testimonialText;

      // Insert Testimonial Signature
      let signature = testimonial.Signature;
      innerTestimonialSignature.innerHTML = signature;
    });
  };
  request.send();
};

Testing Carousel (have tried alternative with event listeners rather than inline onclick and cannot access the elements printed through the response(returns undefined as the elements are printed after dom load))

let tabIndex = 1;

function nextTestimonial(n) {
  testimonialSlide((tabIndex += n));
}

function currentTestimonial(n) {
  testimonialSlide((tabIndex = n));
}

function testimonialSlide(n) {
  let innerTestimonials = document.querySelectorAll(
    ".inner-testimonial-container"
  );

  if (n > innerTestimonials.length) {
    tabIndex = 1;
  }
  if (n < 1) {
    tabIndex = innerTestimonials.length;
  }
  for (let i = 0; i < innerTestimonials.length; i++) {
    innerTestimonials[i].style.display = "none";
  }
  innerTestimonials[tabIndex - 1].style.display = "block";
}

Random attempt to chain onload functions (this breaks the response)

window.onload = () => {
  const innerTestimonialsNew = document.querySelectorAll(
    ".inner-testimonial-container"
  );
  console.log(innerTestimonialsNew);
};

Saveas function not working chrome is javascript

There is a save button. On clicking the save button i need to save the page on my local system.
I have implemented it using the document.execCommand(‘SaveAs’)
It seems it will work only for IE.
Are there any other ways of implementing the “save as” option so that it works on all browsers.

How to find last text before character x while character y is still behind y Javascript

I was trying to find an elegant solution to the following problem. I have the following string :

This ) is ) some $ text. ) lkzejflez $ aaeea ) aeee

Existing out of a part that is human readable text before the bold marked bracket and a part that just plain rubbish after the bracket. I need to find the human readable text in string alike this one. I need to get the text before the last bracket (bold marked) that still has a dollar sign (bold marked) behind it. Here is my solution to the problem :

const info = "This)is)$a sentence.)lkzejflez$aaeea)aeee";
let result;

for(let i = 0; i < info.length;i++){
  const char = info[i];
  const after = info.substr(i+1,info.length);
  const otherChance = after.indexOf(')') < after.lastIndexOf('$');
  if(otherChance){continue;};
  const isEndBracket = char ===')';
  const before = info.substr(0,i)
  if(isEndBracket){result = before;break;};
}
console.log(result)

The expected result is ‘This)is)$a sentence.’ My code does return this result but it uses substr and a forloop where regex could be used. I do however not now how. Does anyone know a more elegant solution to my problem. Thanks in advance.

Mapping data from JSON sourced from Fetch API

As a newbie to React, I have been struggling with mapping JSON data for a couple days now. What I have below is my App.js file. I am trying to map the data pulled from an external JSON into my array labeled airData and then into the Components further down the page. The data correctly prints to the console but the array seems empty when I try and actually use and map the data. Any direction is appreciated.

My App.js:

const airData = []

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      airData: []
    }
   }

componentDidMount(){

  var myHeaders = new Headers();
      myHeaders.append("Authorization", "Bearer xxxxxxxxx");

      var urlencoded = new URLSearchParams();
      urlencoded.append("macAddress", "xxxxxxxxxx");
      urlencoded.append("mode", "minute");

      var requestOptions = {
      method: 'POST',
      headers: myHeaders,
      body: urlencoded,
      redirect: 'follow'
      };

  fetch("MY_API_URL", requestOptions)
   .then(response => response.text())
   .then(data => {
     console.log(data)
     this.setState({
       airData: data
     })
   });
  }


  
  render () {
        return (
          <div className="app">
            <Header />
            <div className="spacer"></div>
            <OverallStatus />
            {airData.map(data => {
                return (
                  <div>
                    <div className='qualityFactor'>
                      <h1><img src={iconHumidity} alt="Logo" className="iconSmall" />Humidity {data.humidity}%</h1>
                      <ProgressBar completed={data.humidity}
                      maxCompleted={100} className="statusBar" />
                    </div>
                    <div className='qualityFactor'>
                      <h1><img src={iconAirPressure} alt="Logo" className="iconSmall" />Air Pressure {data.AirPressure} hPa</h1>
                      <ProgressBar completed={data.AirPressure}
                      maxCompleted={1030} className="statusBar" />
                    </div>
                    <div className='qualityFactor'>
                      <h1><img src={iconCarbonDioxide} alt="Logo" className="iconSmall" />Carbon Dioxide {data.CO2} ppm</h1>
                      <ProgressBar completed={data.CO2}
                      maxCompleted={2000} className="statusBar" />
                    </div>
                    <div className='qualityFactor'>
                      <h1><img src={iconVOCs} alt="Logo" className="iconSmall" />Chemicals {data.TVOC} ppb</h1>
                      <ProgressBar completed={data.TVOC}
                      maxCompleted={1000} className="statusBar" />
                    </div>
                    <div className='qualityFactor'>
                      <h1><img src={iconParticulateMatter} alt="Logo" className="iconSmall" />Particles {data.PM25} ug/m3</h1>
                      <ProgressBar completed={data.PM25}
                      maxCompleted={100} className="statusBar" />
                    </div>
                    <div className='qualityFactor'>
                      <h1><img src={iconCarbonMonoxide} alt="Logo" className="iconSmall" />Carbon Monoxide {data.CO} ppm</h1>
                      <ProgressBar completed={data.CO}
                      maxCompleted={100} className="statusBar" />
                    </div>
                    <div className='qualityFactor'>
                      <h1><img src={iconNitrogenDioxide} alt="Logo" className="iconSmall" />Nitrogen Dioxide {data.NO2} ppb</h1>
                      <ProgressBar completed={data.NO2}
                      maxCompleted={200} className="statusBar" />
                    </div>
                    <div className='qualityFactor'>
                      <h1><img src={iconOzone} alt="Logo" className="iconSmall" />Ozone {data.Ozone} ppb</h1>
                      <ProgressBar completed={data.Ozone}
                      maxCompleted={100} className="statusBar" />
                    </div>
                  </div>
              );})}
          </div>
        )
    }
  }
  
  

export default App;

useState does not work with another prop function which uses dispatch from useReducer

I have a function contains prop function and useState hook together that attached onClick event.

When event was fired, prop function works but my local useState hook does not work. If I delete prop function, everything is okay and hook is running. I can not understand why my hook does not work with prop function.

You can see the function. props.add works fine but setBookmarked doesnt work.

And here, you can check my prop function.

Any idea?

“Cannot GET / ” webpack-dev-server

In order to prevent this question being marked as duplicate, I want to mention that I have referred to a number of similar SO questions and tried the accepted/most upvoted answers, but those did not help:

  1. webpack-dev-server ‘Cannot GET /’
  2. Cannot GET / – localhost 8080 not working with webpack dev server
  3. Cannot GET / error running hello world in webpack
  4. Plugin not defined in webpack configuration file

I am trying to create a simple Javascript application which uses RxJs, by following the tutorial at https://www.javatpoint.com/rxjs-first-example.

When I start webpack-dev-server, I get “Cannot GET /” error.

I have committed the code here to a git repository for it to be reproduced easily. Here are the steps:

git clone https://github.com/phalgunv/basic-rxjs-starter.git
npm run start

Open “http://localhost:8080/”, I get the error
enter image description here

What am I missing here?

Most efficient code to add a dollar sign behind a negative/positive number in JS

I have two prices, A and B, and I want to show A - B with a dollar sign.

Example:
A: 10, B: 30 => -$20
A: 40, B: 5  => $35

It is possible to use this function:

function minus(A, B) {
    return `${A-B < 0 && "-"}$${Math.abs(A-B)}`
}

I’am just wondering if it’s the most efficient way (in terms of speed & performance) to do this, or there’s a wiser (!) (and maybe faster) approach.

replacing every instance of a link with another link

I am scraping and modifying content from a website. The website consists of broken images that I need to fix. My JSON looks something like this

[
  {
    "post_title": "post 1",
    "post_link": "link 1",
    "post_date": "@1550725200",
    "post_content": [
      "<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna <a href="somelink.com">aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.<a href="url1.jpg"><img src="brokenURL1.jpg" alt=""></a><a href="url2.jpg"><img src="brokenURL2.jpg" alt=""></a><a href="url3.jpg"><img src="brokenURL3.jpg" alt=""></a><a href="url4.jpg"><img src="brokenURL4.jpg" alt=""></a></p>"
    ],
    "custom": {
      "image": "thumbnail.jpg"
    }
  },
{
    "post_title": "post 2",
    "post_link": "link 2",
    "post_date": "@1550725200",
    "post_content": [
      "<p>At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, <a href="somelink.com">similique</a> sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga.<a href="url5.jpg"><img src="brokenURL5.jpg" alt=""></a><a href="url6.jpg"><img src="brokenURL6.jpg" alt=""></a><a href="url7.jpg"><img src="brokenURL7.jpg" alt=""></a></p>"
    ],
    "custom": {
      "image": "thumbnail.jpg"
    }
  },
{
    "post_title": "post 3",
    "post_link": "link 3",
    "post_date": "@1550725200",
    "post_content": [
      "<p>Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. <a href="url8.jpg"><img src="brokenURL8.jpg" alt=""></a></p>"
    ],
    "custom": {
      "image": "thumbnail.jpg"
    }
  },
{
    "post_title": "post 4",
    "post_link": "link 4",
    "post_date": "@1550725200",
    "post_content": [
      "<p>Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis <a href="somelink.com">doloribus asperiores repellat</a>.<a href="url9.jpg"><img src="brokenURL9.jpg" alt=""></a><a href="url10.jpg"><img src="brokenURL10.jpg" alt=""></a><a href="url11.jpg"><img src="brokenURL11.jpg" alt=""></a></p>"
    ],
    "custom": {
      "image": "thumbnail.jpg"
    }
  }
]

I have the image links and I want to replace every instance of the src link with the a href link. So the end result would look something like this.

[
  {
    "post_title": "post 1",
    "post_link": "link 1",
    "post_date": "@1550725200",
    "post_content": [
      "<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna <a href="somelink.com">aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.<a href="url1.jpg"><img src="url1.jpg" alt=""></a><a href="url2.jpg"><img src="url2.jpg" alt=""></a><a href="url3.jpg"><img src="url3.jpg" alt=""></a><a href="url4.jpg"><img src="url4.jpg" alt=""></a></p>"
    ],
    "custom": {
      "image": "thumbnail.jpg"
    }
  },
{
    "post_title": "post 2",
    "post_link": "link 2",
    "post_date": "@1550725200",
    "post_content": [
      "<p>At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, <a href="somelink.com">similique</a> sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga.<a href="url5.jpg"><img src="url5.jpg" alt=""></a><a href="url6.jpg"><img src="url6.jpg" alt=""></a><a href="url7.jpg"><img src="url7.jpg" alt=""></a></p>"
    ],
    "custom": {
      "image": "thumbnail.jpg"
    }
  },
{
    "post_title": "post 3",
    "post_link": "link 3",
    "post_date": "@1550725200",
    "post_content": [
      "<p>Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. <a href="url8.jpg"><img src="url8.jpg" alt=""></a></p>"
    ],
    "custom": {
      "image": "thumbnail.jpg"
    }
  },
{
    "post_title": "post 4",
    "post_link": "link 4",
    "post_date": "@1550725200",
    "post_content": [
      "<p>Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis <a href="somelink.com">doloribus asperiores repellat</a>.<a href="url9.jpg"><img src="url9.jpg" alt=""></a><a href="url10.jpg"><img src="url10.jpg" alt=""></a><a href="url11.jpg"><img src="url11.jpg" alt=""></a></p>"
    ],
    "custom": {
      "image": "thumbnail.jpg"
    }
  }
]

I also have random links that are not associated with images and are just links like in post 1, 2 and 4. Is there any way to do this with Javascript?

Thanks

Highlight menu item onclicl

I have found several questions to this. I am trying to highlight a selected menu item.

The current code I am using is

<script src="JavaScript/jquery-1.10.2.js" type="text/javascript"></script>

<script>
function active_menu() {
    var url = window.location.href;
    $('.nav a').filter(function() {
        return this.href == url;
    }).addClass('current');
}
</script>
<!--Start Menu -->
  <ul id="nav">
      <li><a href="index.php">Home</a></li>
      <li><a href="runetable.php">Rune List</a></li>
      <li><a href="alpha.php">Runic Alphabet</a>
      <li><a href="trans.php">Runic Transliteration</a></li>
      <li><a href="aetts.php">The Aetts</a></li>
      <li><a href="runes.php">Runes</a>
          <ul>
          <li>Freya's Aett</li>
          <li><a href="fehu.php">Fehu</li>
          <li>Uruz</li>
          <li>Thurisaz</li>
          <li>Ansuz</li>
          <li>Raidho</li>
          <li>Kenaz</li>
          <li>Gebo</li>
          <li>Wunjo</li>
          <li>Hagal's Aett</li>
          <li>Hagalaz</li>
          <li>Nauthiz</li>
          <li>Isa</li>
          <li>Jera</li>
          <li>Eiwaz</li>
          <li>Perthro</li>
          <li><a href="algiz.php">Algiz</a></li>
          <li>Sowilo</li>
          <li>Tyr's Aett</li>
          <li>Tyr</li>
          <li>Berkana</li>
          <li>Ehwaz</li>
          <li>Mannaz</li>
          <li>Laguz</li>
          <li>Inguz</li>
          <li>Dagaz</li>
          <li>Othila</li>
          </ul>
        </li>
      <li><a href="about.php">About</a></li>
      <li><a href="contact.php">Contact</a></li>
  </ul>

<!-- End Menu -->

This code works… Sort of…
I have found maybe 5 or 6 examples and I have run into the same problem with all of them.

Items 2, 6, and 7 will not highlight. That would be Rune List, Runes, and About.

I do not understand why these entries will not highlight, no matter which solution I try. As I said, I have tried a few and they all work except for those menu items.

Can anyone point me in the right direction? I am going nucking futs trying to figure this out.

Thanks for reading!
Jim

Fetch information from API call

I am trying to fetch the temperature etc from the Open Weather API but cannot seem to get it to be able to display information about the actual weather. Using the person’s location to give me the weather at that point and use this to send notifications to the user.

Here is my code below:

import React, {useEffect, useState} from 'react'
import {Text, View, StylesSheet} from 'react-native'


export default function Weather () {
  const [ weather, setWeather] = useState({});
  const API_KEY = './lib/APIKey.js';
  const URL = `https://api.openweathermap.org/data/2.5/weather?lat=${this.coords.latitude}&lon=${this.coords.longitude}&units=metric&APPID=${API_KEY}`;

  async function getWeather() {
    const data = await fetch(URL).then(res => res.json());
    setWeather(data);
  }

  useEffect(() => {
    getWeather();
  })
  }

I’m trying to get the info and use it on another page. I do not need to display the information just need it for the back end and allow me to use the data to send triggered notifications.

Any help would be much appreciated.

Trying to create a Vue 3 application with Cytoscape.JS

Lately, I’ve been needing to dip my toes into the front-end world and Vue seems like a good tool. One of the things I need in my application is a graph tool and I think cytoscape.js fit my needs.

That being said, I’ve been looking for a sample that uses vue-cytoscape inside a Vue 3 typescript application but so far have found nothing.

Is it possible to do so? Or does Cytoscape only works inside Vue 2 as of the moment?

Unexpected token error when trying to authenticate React signup through Django

I would like to enable my React front end to consume my Django API enabling users to signup, for a user to be created on Django and to be logged in and redirected to a ‘profile page’

I however keep encountering this error message when trying to npm start by React App

Here is an overview of the structure of my project

--django-project
----peerplatform
------accounts
      models.py
      serializers.py
      urls.py
------signup
      urls.py
------peerplatform-fe
---------src
-----------components
-------------login_components
             Login.js
-------------signup_components
             Signup.js
-------------profile_components
             Profile.js
------------views
            Home.js

This is my code on Login.js

import React, { Component,useState,useEffect } from "react";
import secure_login from "../../assets/images/secure_login.svg"
import "../../assets/scss/core/signup_components/_signup.scss"

export default class Login extends Component {
    constructor(props) {
        super(props);
    }
    const [email, setEmail] = useState('');
    const [password, setPassword] = useState('');
    const [errors, setErrors] = useState(false);
    const [loading, setLoading] = useState(true);

    useEffect(() => {
        if (localStorage.getItem('token') !==null) {
            window.location.replace('http://localhost:3000/profile');
        } else {
            setLoading(false);
        }
    }, []);

    const onSubmit = e => {
        e.preventDefault();
    }

    const user = {
        email: email,
        password: password
    };

    fetch('http://127.0.0.1:8000/api/v1/users/', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(user)
    })
        .then(res => console.log(res.json()))
        .then(data => {
            if(data.key) {
                localStorage.clear();
                localStorage.setItem('token',data.key);
                window.location.replace('http://localhost:3000/profile');
            } else {
                setEmail('');
                setPassword('');
                localStorage.clear();
                setErrors(true);
            }
        });
    };

    render() {
    return (
      <div className="base-container" ref={this.props.containerRef}>
        <div className="header">Login</div>
        <div className="content">
          <div className="image">
            <img src={secure_login} />
          </div>
          <div className="form">
            <div className="form-group">
              <label htmlFor="username">Username</label>
              <input type="text" name="username" placeholder="username" />
            </div>
            <div className="form-group">
              <label htmlFor="password">Password</label>
              <input type="password" name="password" placeholder="password" />
            </div>
          </div>
        </div>
        <div className="footer">
          <button type="button" className="btn">
            Login
          </button>
        </div>
      </div>
    );
  }
}

Signup.js

import React, { Component,useState,useEffect } from "react";
import secure_signup from "../../assets/images/secure_signup.svg"
import CountrySelector from './CountryList'
import ProcessImage from 'react-imgpro';


export default class Signup extends Component {
    constructor(props) {
        super(props);
    }
    state= {
        src:'',
        err:null
    }
    const [email,setEmail] = useState('');
    const [password1, setPassword1] = useState('');
    const [location, setLocation] = useState('');
    const [errors,setErrors] = useState(false);
    const [loading, setLoading] = useState(true);

    useEffect(() => {
        if(localStorage.getItem('token') !== null) {
            window.location.replace('http://localhost:3000/profile');
        } else {
            setLoading(false);
        }
    }, []);

    const onSubmit = e => {
        e.preventDefault();

        const user = {
            email: email,
            password: password,
            location: location
        };

        fetch('http://127.0.0.1:8000/api/v1/users/profiles/', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(user)
            })
            .then(res => res.json())
            .then(data => {
                if(data.key) {
                    localStorage.clear();
                    localStorage.setItem('token',data.key);
                    window.location.replace('http://localhost:3000/profile');
                } else {
                    setEmail('');
                    setPassword1('')
                    setLocation('')
                    localStorage.clear();
                    setErrors(true);
                }
            });
        }
    }
      render() {
        return (
            <div className="base-container" ref={this.props.containerRef}>
                {loading === false && <div className="header">Register</div> }
                {errors === true && <h2>Cannot signup with provided credentials</h2>}
                <div className="content">
                    <div className="image">
                        <ProcessImage
                            image={secure_signup}
                            resize={{ width:400, height: 400 }}
                            processedImage={(src,err) => this.setState({ src,err})}
                            />
                    </div>
                    <div className="form">
                        <div className="form-group">
                            <label htmlFor="username">Username</label>
                            <input
                                type="text"
                                name="name"
                                placeholder="name"
                                value={name}
                                onChange={e => setEmail(e.target.value)}
                                required
                            />{' '}
                        </div>
                        <div className="form-group">
                            <label htmlFor="email">Email</label>
                            <input
                                type="text"
                                name="email"
                                placeholder="email"
                                value={email}
                                onChange={e => setEmail(e.target.value)}
                                required
                            />{' '}
                        </div>
                        <div className="form-group">
                            <label htmlFor="location">Location</label>
                            <CountrySelector />
                        </div>
                        <div className="form-group">
                            <label htmlFor="password">Password</label>
                            <input
                                type="text"
                                name="password"
                                placeholder="password"
                                value={password}
                                onChange={e => setPassword1(e.target.value)}
                                required
                            />
                        </div>
                    </div>
                </div>
            <div className="footer">
                <button type="button" className="btn" onClick={onSubmit}>
                    Register
                </button>
            </div>
        </div>
      );
    }
}

App.js

import React, { useRef, useEffect } from 'react';
import { useLocation, Switch } from 'react-router-dom';
import AppRoute from './utils/AppRoute';
import ScrollReveal from './utils/ScrollReveal';
import ReactGA from 'react-ga';
import Login from './components/login_components/Login';
import Signup from './components/signup_components/Signup'
import Profile from './components/profile_components/Profile'

// Layouts
import LayoutDefault from './layouts/LayoutDefault';

// Views 
import Home from './views/Home';

// Initialize Google Analytics
ReactGA.initialize(process.env.REACT_APP_GA_CODE);

const trackPage = page => {
  ReactGA.set({ page });
  ReactGA.pageview(page);
};

const App = () => {

  const childRef = useRef();
  let location = useLocation();

  useEffect(() => {
    const page = location.pathname;
    document.body.classList.add('is-loaded')
    childRef.current.init();
    trackPage(page);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [location]);

  return (
    <ScrollReveal
      ref={childRef}
      children={() => (
        <Switch>
          <AppRoute exact path="/" component={Home} layout={LayoutDefault} />
          <AppRoute exact path="/login" component={Login} />
          <AppRoute exact path="/signup" component={Signup} />
          <AppRoute exact path="/profile" component={Profile} />
        </Switch>
      )} />
  );
}

export default App;

serializers.py

from rest_framework import serializers
from .models import Profile

class ProfileSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Profile
        fields = ('user_id', 'name', 'location', 'password', 'email', 'signup_confirmation')

When I try to run my code I get the error:

./src/components/signup_components/Signup.js
  Line 15:11:  Parsing error: Unexpected token

  13 |         err:null
  14 |     }
> 15 |     const [email,setEmail] = useState('');
     |           ^
  16 |     const [password1, setPassword1] = useState('');
  17 |     const [location, setLocation] = useState('');
  18 |     const [errors,setErrors] = useState(false);

I don’t get where the unexpected token error is coming from

back button not working properly (chrome)

I have a request axios(vue):

.then(response => {
  history.pushState(null, null, response.request.responseURL);
}

Standart URL – http://localhost:30/shop. With this line, I complete the URL. in the end it will look like: http://localhost:30/shop?tags[]=5

But when I go to another page (http://localhost:30/shop/parts/2123 ) and then click the back button. Then I see not the page, but the response of the request (just text).

How i can resolve this problem?

upd: with FF working fine. Only when using google chrome.