I encountered an issue while attempting to add new data to an array

I am currently working on implementing a tree structure.

My main goals are to add, delete, edit, and search data within the tree.

However, when I try to push new data into an array, I encounter an error where it says:

TypeError: treeData.push is not a function

I need assistance in storing the data in a new variable before pushing it into the array...

DragandDrop.js:

import React, {
    useState,
    Component,
    useEffect
} from "react";
import 'react-sortable-tree/style.css';
import {
    removeNodeAtPath
} from 'react-sortable-tree';
import SortableTree from 'react-sortable-tree';
import {
    toggleExpandedForAll
} from 'react-sortable-tree';
import './styles.css'


const Treeview = (props, reset) => {
    console.log('props', props)

    const initTreeData = [{
            title: 'Data_1',
            children: [{
                title: "Data_2"
            }]
        },
        {
            title: 'Data_1'
        },
        {
            title: 'Data_2'
        }
    ]
    console.log('test', initTreeData.length)

    var test = {
        index: initTreeData.length + 1,
        title: props.info
    }

    useEffect(() => {
        _fetchGeneral();
    }, [])

    const [treeData, setTreeData] = useState(initTreeData);

    console.log(treeData, "*******")
    if (test.title != '') {
        var m = treeData.push(test)
        // setTreeData(m);
    }

    const _fetchGeneral = async () => {
        setTreeData(initTreeData);
    }

    const updateTreeData = (e) => {
        setTreeData(e);
    }

    // Expand and collapse code 
    const expand = (expanded) => {
        setTreeData(toggleExpandedForAll({
            treeData: treeData,
            expanded,
        }), );
    }

    const expandAll = () => {
        expand(true);
    }

    const collapseAll = () => {
        expand(false);
    }

    // Expand and collapse code  end

    // remove node 
    const removeNode = (rowInfo) => {
        let {
            node,
            treeIndex,
            path
        } = rowInfo;

        setTreeData(removeNodeAtPath({
            treeData: treeData,
            path: path, // You can use path from here
            getNodeKey: ({
                node: TreeNode,
                treeIndex: number
            }) => {
                console.log(number, 'event');
                return (number);
            },
            ignoreCollapsed: false,
        }))
    }

    // remove node end

    return (
        <
        div style={{display: 'flex', flexDirection: 'column', height: '100vh'}}>
        <
        div style={{flex: '0 0 auto', padding: '0 15px'}}>
        <
        h3> Full Node Drag Theme</h3>
        <
        button onClick={expandAll}> Expand All</button>
        <
        button onClick={collapseAll}> Collapse All</button> &
        nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp;


        <
        /div>

        <
        div style={{flex: '1 0 50%', padding: '0 0 0 15px'}}>
        <
        SortableTree className="tree-dt" id="add_name" treeData={treeData} onChange={updateTreeData}
        generateNodeProps={rowInfo => ({
            buttons: [
            <
            div>
            <
            button label='Delete' onClick={()=> removeNode(rowInfo)}> X< /button> < /
            div >,],
            style: {height: '50px',}})}
        canDrag={({node})=>!node.dragDisabled} 
        /> < /
        div> <
        /div>
      </div>
  </div>
</p>
<p><strong>Add.js File</strong>:</p>
<p><div>
  <div>
    <pre class="lang-js"><code>import React, {useState} from 'react';
import {TextField} from '@fluentui/react/lib/TextField';
import {DefaultButton, PrimaryButton, Stack, IStackTokens} from '@fluentui/react';
import './styles.css'


const TextFieldBasicExample = (props) => {
    const [newItemValue, setNewItemValue] = useState({title: ''});
    console.log('onchange', newItemValue);

    const handleChange = (e) => {
      setNewItemValue({
          [e.target.name]: e.target.value,
      });
    }
    const _insert = (event) => {
      console.log('onclick', newItemValue);
      props.callback(newItemValue);

      // setNewItem({
      //   [event.target.name]:''
      // })
    }

    return (
      <
      Stack horizontal>
      <
      Stack className="add-inp">

      <
      TextField label="Add Item" name="title" onChange={handleChange}/> 
      <
      span id="error_name"></span> 
      <
      PrimaryButton text="Add" className="add-btn" onClick={_insert}/>

      <
      /Stack> 
      <
      /Stack>


    );
};

export default TextFieldBasicExample

app.js file:

import React, {
      useState,
      Component,
      useEffect
  } from "react";
  import 'react-sortable-tree/style.css';
  import TreeView from "./Drag&Drop";
  // import Test from "./Testing";
  import AddEdit from "./Add";
  import './styles.css'

  const Tree = (props) => {
      const [info, setInfo] = useState('');
      const data = (item) => {
          let value = item.title;
          setInfo(value);
      }
      console.log('data', info)
      return (<
        div>
        <
        div className="add-dt">
        <
        div className="left-side">
        <
        AddEdit callback={data}/>
        <
        /div> 
        <
        div className="right-side">
        <
        TreeView info={info}/>
        <
        /div> 
        <
        /div> 

        <
        /div>
      );
  }

  export default Tree;

Answer №1

It seems like you might be encountering a problem with the following piece of code:

if (test.title != '') {
    var m = treeData.push(test)
    // setTreeData(m);
    }

To address this issue, you can modify it as shown below:

if (test.title != '') {
    setTreeData([...treeData, test]);
    }

Answer №2

You can experiment with using useState to store an array of strings by trying either useState<string[]>(defaultValues) or simply useState([])

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Adjustments to CSS resulting from modifications made with react-router-dom

Currently working on a petite website using create-react-app combined with sass, I aim to have the ability to alter the styling of Navbar.Brand. This includes the feature to conceal it when the homepage is in view, depending on the URL path. I believe an ...

What is the best way to display the outcome in a popup window?

I am looking to display the result in a pop-up window. Code: <?php $con=mysqli_connect("localhost","root","1234","fyp"); // Check connection if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } $result = ...

Extension: What is the best way to leverage data obtained from an ajax request in order to dynamically modify an already existing element within

I've been trying to find a reliable and comprehensive tutorial for JavaScript (JS) and Ajax, but so far my search has been futile. Unlike Python.org for Python or php.net for PHP, I haven't found a satisfactory resource yet. Any recommendations w ...

Encountered a problem while assigning a function to a variable

I'm currently working with a function that retrieves images based on a search query. Here's the code: function getImage(query){ var serach_title = query.replace(/\ /g, '+'); var imgUrl = "https://ajax.googleapis.com/ajax/s ...

Unpredictable term pulled from the Javascript/Ajax content

Can someone help me figure out how to randomly select just one word from a block of text using JavaScript? Here's the code I've been working with: function someFunction() { // need help here var word; $.ajax({ async: false, typ ...

Prevent form submission once all tasks have been finalized

Hey there, I've been racking my brain for hours trying to solve this issue... I'm looking to disable my form after it's been submitted to prevent multiple submissions. However, every method I try seems to disable the button but also interfe ...

What is the process for displaying information from a database on a model popup box?

I am working on displaying books in the Index view that are retrieved from a database. Each book has a button underneath it. The goal is to have a modal box appear when these buttons are clicked, showing details of the corresponding book such as the book i ...

A step-by-step guide on executing a callback function once the animation has finished with frame-motion

I'm facing an issue with my component called AnimatedText. After the animation is complete, I want the words filled in the underlineLines prop to be underlined. How can I achieve this? I attempted using the onAnimationEnd function, but it didn't ...

Is it possible to include a JavaScript file within a partial view in ASP.NET MVC?

In my asp.net-mvc website, the top section contains filter information while the middle section displays reports. I have several different report formats that I want to toggle between. Currently, I am using partial views loaded via ajax to switch between r ...

Executing a JavaScript function through a hyperlink created by an AJAX request

Having a JavaScript function here. I am performing an AJAX call, and within the received content, there is a link that needs to trigger the JavaScript function. MyJavascriptFunction(bla){ alert (bla); } ...

Is it possible to display multiple slideshows in separate tabs on a single page simultaneously?

I am trying to create multiple slideshows, each in a different tab on the same page. Although I am not an expert, I am attempting to figure out how to have the slideshow repeat with buttons controlling each one separately. When adding the complete script ...

Using jQuery to apply a class based on JSON data

This file contains JSON data with details about seat information. var jsonData = { "who": "RSNO", "what": "An American Festival", "when": "2013-02-08 19:30", "where": "User Hall - Main Auditorium", "seats": ["0000000000000000001111111 ...

When attempting to create, an error occurs: Uncaught TypeError: Unable to access properties of undefined (retrieving 'id')

In the process of creating a public prayer journal that allows users to include their favorite Bible verses, I encountered an issue while trying to add a prayer or verse. The error message "caught (in promise) TypeError: Cannot read properties of undefined ...

Application unable to save data to file with no indication in error logs

Recently, I've been experimenting with the Capture-Website package, which is designed to save website screenshots to a file. Initially, everything was working smoothly until I decided to restart the server. Now, although my code is running without a ...

Create a versatile 1, 2, 3 column layout that seamlessly transitions from mobile to desktop using Flex

My vision is clear: https://i.sstatic.net/xi7KI.png Flex is the way to go for this, but my attempts are falling short: .content-wrapper, .tablet-top, .tablet-middle, .tablet-bottom { display: flex; justify-content: center; } /*tablet*/ @media ...

How can Vue be used to dynamically change the input type on focus?

What Vue method do you recommend for changing an input element's type on focus? e.g. onfocus="this.type = 'date'" I am specifically looking to switch the input type from text to date in order to utilize the placeholder property. ...

Disabling comments is creating problems with the appearance of Wordpress pages

Visit handheldtesting.com Whenever the option "disable comments" is selected in the backend, or if 'display:none:' is added <div id="respond" class="comment-respond" style="display:none;"> to the code, half of the content on the page dis ...

Issue with loading Three.js asynchronously

My attempt to determine the maximum value of a point cloud data using the following code proved unsuccessful. import { PLYLoader } from "three/examples/jsm/loaders/PLYLoader"; let max_x = -Infinity; function initModel() { new PLYLoader().load ...

Ways to embed one block of javascript code within another block of javascript code

Can you help me with inserting the following code into a specific part of my JavaScript code? The issue I am facing is that the code contains all JavaScript, and when I directly add it, the gallery crashes. <div id='gallerysharebar'> & ...

Hide the selection box when hovering over the Div

Looking for a quick solution. I want the option drop down to close when another div element is hovered over. First, open the drop down and hover over the red element on the right side. When hovering over the red element, I would like the drop down to clos ...