Dynamically generating Formik fields based on JSON

I have a multi-page form written in Formik. Based on responses to a couple of the form fields, an API is called, which returns a JSON object containing questions that need to be answered.

As you can see in the JSON below, the top level of this JSON array contains questions that would need to be answered every time the form is displayed (in the example, only one question would definitely need to be answered). Within each question, there can be an “answerYes” or “answerNo” key. The value associated with either of these keys is identical to the top level question element. Additionally, the second level question element can contain another “answerYes”/”answerNo” key and this can happen indefinitely.

These “answerYes”/”answerNo” questions need to be dynamically generated as Formik Fields, based on the answer to the top level question. This needs to be possible for any depth of questions – i.e. second level, third level, fourth level, etc.

Can anyone think of an elegant way to do this using Formik Fields based on the JSON below?

[
    {
        "questionCode": "APPLE-1",
        "question": "Do you like apples?",
        "answerNo": {
            "questionCode": "APPLE-2",
            "question": "Are you sure you don't like apples?",
            "answerYes": {
                "questionCode": "APPLE-3",
                "question": "Ok, do you like oranges?",
                "answerYes": {
                    "questionCode": "ORANGE-1",
                    "question": "Ok, but do you like peeling oranges?"
                }
            }
        }
    }
]

API is being called over and over again on react [duplicate]

Before I start: There is a similar question on this website but the answer to it does not fit with our code.

For a school project, we are using RestDB to hold json data of 15 SCP subjects. We are using hooks to get this data, and then putting it inside of vars so that we can loop through them and only display that one we need, so the user can press a button, and that SCP will load.

The problem is, while its working, its calling the API over and over and over again, having the web app open for 15 minutes and it seemingly calls it endlessly.

Just my (best) guess this snippet is at fault:

return(
    <div className="container">
        {
        currentState && currentState.map(
            scp => {
                ScpNumCopy[temp] = scp.scpNumber;
                ScpOCCopy[temp] = scp.objectClass;
                ScpCPCopy[temp] = scp.scp;
                ScpDescCopy[temp] = scp.description;
                ScpRefCopy[temp] = scp.referenece;
                ScpOthCopy[temp] = scp.other;
                ScpImgCopy[temp] = scp.img; // Assigning the JSON data into vars
                temp = temp+1; // using map as a for loop to do this
                if (ScpRefCopy[uInput] === "" ) {
                    ref = "";
                } 
                if (ScpOthCopy[uInput] === "" ) { // these two are just here to produce nill if there is no ref or oth so they dont show up
                    oth = "";
                }
            }
        )
        }
        <img src={ScpImgCopy[uInput]} alt={ScpNumCopy[uInput]} class="images" id="Floatin"/> 
        <p><strong>SCP Number:</strong> {ScpNumCopy[uInput]}</p>
        <p><strong>Object Class:</strong> {ScpOCCopy[uInput]}</p>
        <p><strong>Containment Procedures:</strong> {ScpCPCopy[uInput]}</p>
        <p><strong>Description:</strong> {ScpDescCopy[uInput]}</p>
        <p><strong>{ref}</strong> {ScpRefCopy[uInput]}</p>
        <p><strong>{oth}</strong> {ScpOthCopy[uInput]}</p>
    </div>
); // Displaying the HTML/JS

The entire page

    import { useEffect, useState } from 'react';
import {uInput} from './Entries';

function SCPs()
{
    function LoadSCPs()
    {
        var data = null;

    var xhr = new XMLHttpRequest();
    xhr.withCredentials = false;

    xhr.addEventListener("readystatechange", function () {
    if (this.readyState === 4) {
        console.log("Calling API...");
        const scpData = JSON.parse(this.responseText); // Creates variable as scpdata with json data being parsed
        setState(scpData); // Sets state as scpdata
    }
    });

    xhr.open("GET", "https://scpdatabase-b328.restdb.io/rest/scpfiles");
    xhr.setRequestHeader("content-type", "application/json");
    xhr.setRequestHeader("x-apikey", "628ace9c4cca5010d1293f37");
    xhr.setRequestHeader("cache-control", "no-cache");

    xhr.send(data);
}



// Creates variables for states
const [currentState, setState] = useState([]);

useEffect(
    () => {
        LoadSCPs();
    }, [currentState], // this is where the similar question cant be applied, as we need 
                       //the array to havve currentState in it, not empty
);
  

var ref = "References:";
var oth = "Other Information:"; // these two are here, so that if they are empty on the SCP subject, we can make it nill instead of loading anything


var ScpNumCopy = [];
var ScpOCCopy = [];
var ScpCPCopy = [];
var ScpDescCopy = [];
var ScpRefCopy = [];
var ScpOthCopy = []; 
var ScpImgCopy = []; // making vars to store JSON data in, so we can go over it by index after the user presses the corresponding button
var temp = 0;



return(
    <div className="container">
        {
        currentState && currentState.map(
            scp => {
                ScpNumCopy[temp] = scp.scpNumber;
                ScpOCCopy[temp] = scp.objectClass;
                ScpCPCopy[temp] = scp.scp;
                ScpDescCopy[temp] = scp.description;
                ScpRefCopy[temp] = scp.referenece;
                ScpOthCopy[temp] = scp.other;
                ScpImgCopy[temp] = scp.img; // Assigning the JSON data into vars
                temp = temp+1; // using map as a for loop to do this
                if (ScpRefCopy[uInput] === "" ) {
                    ref = "";
                } 
                if (ScpOthCopy[uInput] === "" ) { // these two are just here to produce nill if there is no ref or oth so they dont show up
                    oth = "";
                }
            }
        )
        }
        <img src={ScpImgCopy[uInput]} alt={ScpNumCopy[uInput]} class="images" id="Floatin"/> 
        <p><strong>SCP Number:</strong> {ScpNumCopy[uInput]}</p>
        <p><strong>Object Class:</strong> {ScpOCCopy[uInput]}</p>
        <p><strong>Containment Procedures:</strong> {ScpCPCopy[uInput]}</p>
        <p><strong>Description:</strong> {ScpDescCopy[uInput]}</p>
        <p><strong>{ref}</strong> {ScpRefCopy[uInput]}</p>
        <p><strong>{oth}</strong> {ScpOthCopy[uInput]}</p> // Displaying the HTML/JS
    </div>
);  
}



export default SCPs;   

This is the first time we are doing this, so while I’m sure it is super inefficient, we will pickup how to do this better as we make more to practice, just need to figure out why its calling the data over and over again.

As a side note: The buttons and how the functions of calling that SCP entry are on a different page, if the code needs drastic overhauls than we can change the other pages as needed, more than likely without help.

Thanks

How to pass data from async fuction to useState() Flask API + React Frontend

I’m trying to get the state of my hue lights using my API and based on this information render the page ( basically if my lamp is on I want my toggle switch on website to be already toggled once the page loads) Currently I’m trying pass data fetched from my API using async function to the useState()

Here is my code

const LightSwitch = (props) => {

  async function lightState(){
    const response = await httpGet('http://192.168.1.124/get_light_state/id/' + props.id);
    let data = await response
    return data;
  } 

  lightState().then(data => {
    console.log(data.Light);
  }
    )

    const [toggleSwitch, setToggleSwitch] = useState();

My API response is

{
  "Light": false
}

Here is my whole code for reference.

import React, { useState } from "react";
import { Switch } from "antd";
import "./LightSwitch.css";

async function httpGet (url){
  const response = await fetch(url,{method: 'GET'});
  const string = await response.text();
  const json = string === "" ? {} : JSON.parse(string);
  return json;
  
}
const LightSwitch = (props) => {

  async function lightState(){
    const response = await httpGet('http://192.168.1.124/get_light_state/id/' + props.id);
    let data = await response
    return data;
  } 

  lightState().then(data => {
    console.log(data.Light);
  }
    )

    const [toggleSwitch, setToggleSwitch] = useState();

  
  const onChangeSwitch = (checked) => {
    setToggleSwitch(!toggleSwitch);
    if (checked) {
      console.log(props.name + ' on');
      httpGet('http://192.168.1.124/turn_on/id/' + props.id);
    }else{
      console.log(props.name + ' off');
      httpGet('http://192.168.1.124/turn_off/id/'+ props.id);
    }

  };

  return (
    <div>
      <Switch checked={toggleSwitch} onChange={onChangeSwitch}></Switch>
    </div>
  );
};
export default LightSwitch;

Prevent enter from submitting from without it being in a form

I have found this demo online of a replication of the tag adding feature in stack overflow. As you can see with the demo, the javascript allows for , or enter to submit a new tag. However, I would like to disable both these features.

https://jsfiddle.net/2gvdsvos/4/

It is quite easy to disable the , button, but I am having some trouble with the enter button as it is not in a form, nor can it be in a form. I want all the code to stay the same, except for the javascript. Hope someone can help me.

JavaScript: Possibly Asynchronous vs Synchronous For Loop issue? Or some other mistake?

Doing a JavaScript assingment: I need to create a game where the user tries to correctly guess 4 random numbers from 1-6. Ex. 1 3 2 4 or 1 6 5 3 or etc.
The computer should analyze it and tell the player (a) how many of his or her guessed digits were correct, but in the wrong place, and (b) how many of the guessed digits were correct and in the right place.

Example below (bold = user inputs):

Welcome to Mastermind

Please enter your four numerical guesses (space separated): 2 4 3 1

You have 2 correct number(s) and 1 correct location(s).

Please enter your four numerical guesses (space separated): 4 5 3 2

Correct!

You are a MasterMind!

However in my code, where I count the number of correct numbers in wrong positions and right positions, the console outputs wrong numbers.
I make copies of the correctAnswerList and userGuessList. So if the user guess matches with the correct answer, I change the numbers in these copies(outside of the 1-6 range) so they aren’t recounted.
I tried to search on google what could be my issue since I’m new to Javascript. Read some things about asynch for loops but don’t really get it. Code is below, thanks in advance!!

function checkingCorrect(userGuessList, correctAnswerList){
  var correctLocation = 0;
  var correctNumber = 0;
  var copyUserGuessList = userGuessList;
  var copyCorrectAnswerList = correctAnswerList
  
  for(var i = 0; i < 4; i++){
    if(userGuessList[i] == correctAnswerList[i]){
      correctNumber++
    }
    for(var x = 0; x < 4; x++){
      if(copyUserGuessList[i] == copyCorrectAnswerList[x]){
        copyUserGuessList[i] = -1;
        copyCorrectAnswerList[x] = 0;
      }
    }
    if(copyUserGuessList[i] == -1){
    correctNumber++; }
  }
  correctNumber = correctNumber - correctLocation;
  return([correctNumber, correctLocation]);
}

Why my function (marcin) always returns last else? [duplicate]

The script should calculate the price of fuel, depending on its type, but it always returns its last else (“koszt paliwa: 0zł”).

JAVASCRIPT

    var rodzaj = document.getElementById("rodzajPaliwa").value;
  rodzaj = parseInt (rozdaj);
  
    var ilosc = document.getElementById("litry").value;
    ilosc = parseInt (ilosc);
    function pierwszyrodzaj(){
        var typ = 4;
        var suma1 = typ*ilosc;
        document.getElementById("koncowacenapaliwa").innerHTML = "koszt paliwa:" + suma1 + "zł";
    }
    function drugirodzaj(){
        var typ = 3.5;
        var suma2 = typ*ilosc;
        document.getElementById("koncowacenapaliwa").innerHTML = "koszt paliwa:" + suma2 + "zł";
    }
    function inny(){
        document.getElementById("koncowacenapaliwa").innerHTML = "koszt paliwa: 0zł";
    }
    
    function marcin (){
        if(rodzaj == '1'){
            pierwszyrodzaj();
        }else if(rodzaj == '2'){
            drugirodzaj();
        }else{
            inny();
        }
        
    }
    
    document.getElementById("oblicz").onclick = marcin;

HTML

<!DOCTYPE html>
<html lang="pl-PL">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>STACJA PALIW</title>
    <link rel="stylesheet" href="styl3.css">
</head>

<body>

    <div id="baner-lewy">
        <h1>Stacja paliw</h1>
    </div>

    <div id="baner-prawy">
        <a href="index.html">
            <img src="home.png" alt="">
        </a>
        <a href="obliczenia.html">
            <img src="znak.png" alt="">
        </a>
    </div>

    <main>
        <h3>Oblicz koszt paliwa</h3>

        <label for="rodzajPaliwa">Rodzaj paliwa (1-benzyna, 2-olej napędowy): </label><br>
        <input type="number" name="" id="rodzajPaliwa"><br><br>
        <label for="litry">Ile litrów: </label><br>
        <input type="number" id="litry"><br>
        <br>
        <button id="oblicz" >OBLICZ</button>
    </br>
        <span id="koncowacenapaliwa"></span>
  
        <script src="skrypt.js"></script>
    </main>

    <div id="blok-lewy">
        <a href="kwerendy.txt" download="kwerendy">Pobierz kwerendy</a>
    </div>

    <div id="blok-prawy">
        <img src="samochod.png" alt="samochód">
    </div>
    



    <footer id="">
        <p>&copy; Stronę wykonał: Jan Kupczyk 4TID</p>
    </footer>


  
</body>

</html>

That's how the page looks

some more detailssome more detailssome more detailssome more detailssome more detailssome more detailssome more detailssome more detailssome more detailssome more details

React parent component width max-content how to shift child components to second row?

https://codesandbox.io/s/thirsty-maxwell-dr633r?file=/src/App.js

this is the react component I was given, but I want button 2 and button 3 to always be on the 2nd row, with the width of 2nd row be equal to the 1st row. So if the first row is 100px width, the combined length of button 2 and button 3 with padding should be 100px as well on the 2nd row. Everything should be in 1 container. How do i do so?

Add object to array recursively in JavaScript

I’m working with data via the Contentful API and I’m trying to build up a structure of the website I’m building. I’m using the GraphQL API and getting Contentful pages, but, due to rate-limiting, I can’t go super deep with my query when it comes to getting references and hierarchical structure.

This has left me querying my “pages” content type and getting each page and getting its parent page ID, just one level up. The theory being that if I do this for every page, I can build up the page structure recursively by running some JS during the build (I’m using Eleventy to build the site).

I need a function to generate me a breadcrumbs array, ideally I’d give the function a single page’s ID and it would track through the data getting me the details of the parent, the parent’s parent and so on until there are no more parents.

I’ve got the following code, split into two functions at the moment (although not sure if that’s the best approach!)

  /**
   * This takes an ID and finds it within the contentfulPages array (the result
   * of the GraphQL query to Contentful)
   * It returns an object containing the page's ID, slug (for the URL), title
   * (for the readable text) and the parentPageId so we can use that to get the
   * same details for the parent page
   */
  function getParentPage(pageId) {
    const { id, slug, title, parentPageId } = contentfulPages.find(
      (page) => page.id === pageId
    );
    return { id, slug, title, parentPageId };
  }

  /**
   * This takes an ID and passes it to getParentPage to get the first parentPage
   * details. If there is another parent page, it calls itself with the newly 
   * found parent page and pushes that object to the breadcrumbArray. Because it
   * returns the breadcrumb array, each iteration is a more deeply nested array 
   * as opposed to an object at the same level
   */
  function getBreadcrumb(pageId) {
    let breadcrumbArray = [];
    const { id, slug, title, parentPageId } = getParentPage(pageId);
    breadcrumbArray.push({ id, slug, title, parentPageId });
    if (parentPageId) {
      breadcrumbArray.push(getBreadcrumb(parentPageId));
    }
    return breadcrumbArray;
  }

I can see why it’s doing what it’s doing, but I don’t know how to fix it – I want the end result to be a flat array of objects, but the recursive function is causing me problems I think, because I think it has to return something, but I’m not sure how to do that!

An example for a three-levels deep page is this:

// Expected:
[
  {
    id: 'page-3',
    slug: 'courses',
    title: 'Courses',
    parentPageId: 'page-2'
  },
  {
    id: 'page-2',
    slug: 'training',
    title: 'Training',
    parentPageId: 'page-1'
  },
  {
    id: 'page-1',
    slug: 'services',
    title: 'Services',
    parentPageId: false
  },
]


// Actual:
[
  {
    id: 'page-3',
    slug: 'courses',
    title: 'Courses',
    parentPageId: 'page-2'
  },
  [
    {
      id: 'page-2',
      slug: 'training',
      title: 'Training',
      parentPageId: 'page-1'
    },
    [ 
      {
        id: 'page-1',
        slug: 'services',
        title: 'Services',
        parentPageId: false
      },
    ]
  ]
]

Assistance would be much appreciated!

My .map() Not Rendering and I can’t see why?

I cannot for the life of me see what I’m missing that this map function is not rendering anything. I have verified through the console log at the array contains the data that I want. However, when I do the map, nothing shows. There are no errors or warnings, it just doesn’t show anything. I have several other examples of this working just fine the way I’m doing it. I’m sure I’m just not seeing something simple.

import React from 'react';
import { Jumbotron, ProgressBar, Row } from 'react-bootstrap';
import styled from 'styled-components';

const Div = styled.div`
    
    .progressBar{
        background-color: blue;
    }

`

const Budgets = () => {

    const projects = [
     {project_id: 323, project_name: "fake name"}, 
     {project_id: 330, project_name: "fake name2"},
     {project_id: 327, project_name: "fake name3"},
    ];

    
    return (
        <Jumbotron>
            <Div>
                {projects.map((project) => 
                    <h3 key={project.project_id}>{project.project_name}</h3>
                )}
                <h3>This line renders just fine, but the map above does not</h3>
            </Div>
        </Jumbotron>
    )

}
 
export default Budgets;

Jest tests can’t connect to Postgres DB through Knex

I have a whole suite of tests at work that haven’t been run in a while but worked a few months ago. I’d import the global “db” object which is just a knex object with connection info. That stopped working (TypeError: connection.query is not a function).

I read that better practice is to establish the connection in the test script, so I did that. Same error though. Here’s the code:

import knex from 'knex';

const k = knex({
  client: 'pg',
  connection: {
    host: process.env.DATABASE_URL,
    port: process.env.DB_PORT,
    user: process.env.DB_USER,
    password: process.env.DB_PASS,
    database: process.env.DB_NAME,
  },
  debug: true,
});

describe('Tester', async () => {
  test('Test', async done => {
    await k
      .table('test_table')
      .select('id')
      .where({ deleted: false });

    expect(1).toBeGreaterThan(0);
    done();
  });
});

I’ve also tried adding the connection to beforeAll() but that didn’t work either.

The connection info is good (I’ve printed it out and my server is currently running on the same connection info).

The command I’m using to run is

jest testerTest.test.js

Using Node and Postgres

Why won’t my image display on the canvas?

So I have done everything right otherwise another svg file wouldn’t display when I choose to use it.
It finds the correct file path as I am getting no errors on the console, and frankly I’m stumped here.

const body = document.body;
const navButton = document.querySelector('.navTab');
const navMenu = document.querySelector('.nav');

navMenu.style.display = "none";

navButton.addEventListener('mouseover', () => {
    navMenu.style.display = 'flex';
    navMenu.style.flexDirection = "column";
});
navButton.addEventListener('ontouchstart', () => {
    navMenu.style.display = 'flex';
    navMenu.style.flexDirection = "column";
});
navButton.addEventListener('mouseout', () => {
    navMenu.style.display = 'none';
});

const canvas = document.querySelector('canvas');
const ctx = canvas.getContext('2d');
canvas.addEventListener('mouseover', () => {
    canvas.style.opacity = "0.6"
});
const images = ["images/ozzy1.svg","images/ozzy2.jpg","images/ozzy3.jpg"];
const displayImage1 = new Image();
displayImage1.src = images[0]

ctx.drawImage(displayImage1.src = images[0], 0, 0, canvas.width, canvas.height);

So as you can see I’m just calling an image to my canvas, and like I said another image worked. I even tried converting the image I’m attempting to use to an svg, as the image that actually worked was also an svg.