Element type is invalid: expected a string but got undefined, check the render method of `AnimatedComponent` – ReactNavigation

I’m stucking a couple of days with ReactNavigation v6+, also there are several similar questions/answers about the invalid element type, but none of them is working with this simple example:

The issue was started after adding the material-top-tap navigation from @react-navigation module.

To avoid complexity, I use the minimal needed code lines to reproduce this error:

import React from 'react';
import {View, Text} from 'react-native';
import {NavigationContainer} from '@react-navigation/native';
import {createMaterialTopTabNavigator} from '@react-navigation/material-top-tabs';

const TopBarOne = () => (
  <View>
    <Text>TOP BAR ONE</Text>
  </View>
);
const TopBarTwo = () => (
  <View>
    <Text>TOP BAR TWO</Text>
  </View>
);

const TopTabBar = createMaterialTopTabNavigator();

const TopBarStack = () => {
  return (
    <TopTabBar.Navigator>
      <TopTabBar.Screen name={'one'} component={TopBarOne} />
      <TopTabBar.Screen name={'two'} component={TopBarTwo} />
    </TopTabBar.Navigator>
  );
};

const NavigationProvider = () => {
  return (
    <NavigationContainer>
      <TopBarStack />
    </NavigationContainer>
  );
};

export default NavigationProvider;

The complete error log:


ERROR  Error: Element type is invalid: expected a string (for built-in components) or a
class/function (for composite components) but got: undefined.
You likely forgot to export your component from the file it's defined in,
 or you might have mixed up default and named imports.

Check the render method of `AnimatedComponent`.

This error is located at:
    in AnimatedComponent (at createAnimatedComponent.js:264)
    in AnimatedComponentWrapper (at PagerViewAdapter.tsx:123)
    in PagerViewAdapter (at TabView.tsx:79)
    in RCTView (at View.js:32)
    in View (at TabView.tsx:78)
    in TabView (at MaterialTopTabView.tsx:47)
    in MaterialTopTabView (at createMaterialTopTabNavigator.tsx:136)
    in Unknown (at createMaterialTopTabNavigator.tsx:135)
    in MaterialTopTabNavigator (at testProvider.tsx:23)
    in TopBarStack (at testProvider.tsx:33)
    in EnsureSingleNavigator (at BaseNavigationContainer.tsx:430)
    in BaseNavigationContainer (at NavigationContainer.tsx:132)
    in ThemeProvider (at NavigationContainer.tsx:131)
    in NavigationContainerInner (at testProvider.tsx:32)
    in NavigationProvider (at App.tsx:17)
    in App (at hatman/index.tsx:22)
    in Root (at CodePush.js:585)
    in CodePushComponent (at renderApplication.js:50)
    in RCTView (at View.js:32)
    in View (at AppContainer.js:92)
    in RCTView (at View.js:32)
    in View (at AppContainer.js:119)
    in AppContainer (at renderApplication.js:43)

package versions:

"react": "17.0.2",
"react-native": "0.67.2",

"@react-navigation/material-top-tabs": "^6.2.1",
"@react-navigation/native": "^6.0.10",
"@react-navigation/native-stack": "^6.6.1",
"react-native-gesture-handler": "^2.4.0",
"react-native-pager-view": "^6.0.0-rc.1",
"react-native-paper": "^4.12.0",
"react-native-tab-view": "^3.1.1",

targeted device:

Android

Variable in the useState not updating in useEffect callback

const Tweet = ({ tweet, checkedList, setCheckedList }) => {
  const [isChecked, setChecked] = useState(false);
  useEffect(() => {
    checkedList === [] && setChecked(false);
  }, [checkedList, isChecked]);
  return (
    <div className="tweet">
      <h3>Name : {tweet.name} </h3>
      <p>{tweet.tweet}</p>
      <input
        type="checkbox"
        checked={isChecked}
        onChange={() => {
          setChecked(!isChecked);
          checkedList.find((e) => e === tweet.id) === undefined
            ? setCheckedList([...checkedList, tweet.id])
            : setCheckedList(checkedList.filter((e) => e !== tweet.id));
        }}
      />
    </div>
  );
}; 

I have a tweet component that has its own state. There is an external checkedList with is basically an array of checked tweet ids.
But once I reset the checkedList = [] , I am trying to reset the checked tweets by useEffect. But can’t do it.
I want all tweets state to be unchecked. What am I doing wrong?

How can I disable a checkbox until data are load?

I need to disable checkboxes until the page load the data(products) and then enable them again,
this is my code for loading data:

function loadCounter(filterCounter) {
$.each(filterCounter.FilterCounter, function (key, value) {
    if (value.Count !== 0) {
        $("#filter .btn-groupl label :input[value='" + key + "']").parent("label").find("span.items-amount").text(value);
        $("filter .btn-group label :input[value='" + key + "']").parent("label").show();
    } else {
       ;
        $("filter .btn-group label :input[value='" + key + "']").parent("label").hide();
        
    }
});

How to use the same javascript custom package in two different folders without repeating it?

I’m building a microservice and dockerizing it. My folder structure looks as following:

Root
|
|--DockerPacks
   |--ProjectA
      |-docker-compose.yml (builds ServiceA & ServiceB)
|--Microservices
   |--ServiceA
      |-lib
        |-PackageA
      |-src
      |-index.js
      |-Dockerfile
      |-package.json
   |--ServiceB
      |-lib
        |-PackageA
      |-src
      |-index.js
      |-Dockerfile
      |-package.json

So in both services (ServiceA & ServiceB) I need to use the same custom package (PackageA inside lib folder) and I don’t want to have it twice. How could I do this? All help is appreciated.

how can i copy files with all sub-directories to another location on windows in npm script?

I have a project in which in which i have a package.json file which have some build commands.
So in that build command there is copy files to another location. But that command is linux based and is using cp -R for recursive copy to another location. Command piece is like this

cp fonts/ public/css/ -R && cp images/ public/css/ -R

so because in windows there is no cp so i modified this command to this

xcopy fonts/ public/css/ /E && xcopy images/ public/css/ /E

But it’s giving an error of

Invalid number of parameters

How can i resolve this?

Call useQuery api when button is clicked

Using the refetch function useQuery, put the refetch function in the button, and when the button is clicked, the data is fetched again through the api-call. I wanted to, but it didn’t happen.

   
  
 function SeedMaterialDetails(id: number) {
  return axios.get(`/detail/${id}`, {
    headers: {
      "Content-Type": "application/json",
    },
  }) 
} 



  const { data: SeedDetail, refetch: SeedDetaiList } = useQuery(
    ["seedId", seedId],
    () => SeedMaterialDetails(seedId),
    {
      onSuccess: (data) => {
         console.log(data);
      },
      onError: () => {},

      onSettled: (data, context) => {
         
      }
    }
  );

  const [value, setValue] = useState("");
 
  const onChangeValue = (event:  event: React.ChangeEvent<HTMLInputElement>) => {
      setValue(event.target.value)
}

 const handleMaterialSave = useCallback(
    (event: React.ChangeEvent<FormEvent>) => {
      event.preventDefault();
      console.log([value]);
      SeedDetaiList();
    },

    [SeedDetaiList]
  );

return (
<>
 <input 
 type="text"
 value={value}
 onChange={onChangeValue}

 <button onClick={handleMaterialSave}>저장</button>
</>
)

I put the refetch function in handleMaterialSave and when the button works, I thought the useQuery api would call but it doesn’t respond.

I want to call the useQuery api again when I click the Button, but how do I do it?

How to toggle the focus of an input using only JavaScript?

I have been trying to make this thing that focuses an input inside it when its outer div is clicked. I really hope this is not a duplicate as I have searched everywhere and not found an answer to this. I am at risk of being blocked so I hope no one flags this as a duplicate.

Here is the code below, it works with focusing the input, but when it has to unfocus it does not seem to work.

window.onload = function() {
  var drop = document.getElementsByClassName("datadrop");
  var drops = document.getElementsByClassName("datadrop").length;

  for (x = 0; x < drops; x++) {
    var input = document.getElementById(drop[x].getAttribute("input"));
    drop[x].onclick = function(e) {
      e.preventDefault();
      clicked = 0
      if (this == document.activeElement) {
        input.blur();
      } else {
        input.focus();
      }
    }
  }
}
.datadrop {
  padding: 7.5px;
  width: 85px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
}

.datadrop .drop {
  width: 150px;
  position: fixed;
  display: none;
}

.datadrop .item {
  padding: 10px;
}

.datadrop .item:hover {
  background-color: #F1F3F4;
}

.datadrop .divider {
  padding: 5px;
  color: grey;
}

.datadrop .divider:hover {
  background-color: #ffffff;
}

.datadrop input {
  width: 60px;
  color: black;
}

.datadrop:hover {
  background-color: #F1F3F4;
  color: #5F6368;
}

.datadrop .click {
  color: #5F6368;
}

.datadrop input {
  background-color: transparent;
  border: 1px solid transparent;
  outline: none;
  padding: 5px;
}

.datadrop input:focus {
  background-color: white;
  border: 1px solid black;
  border-radius: 2.5px;
}
<div datadrop="scale" input="scales" class="datadrop">
  <input type="text" id="scales" value="100%"> &nbsp;&nbsp;|&nbsp; <i class="fa-solid fa-caret-down click"></i>
  <div class="drop" id="scale">
    <div class="item">Fit</div>
    <div class="item divider">
      <hr>
    </div>
    <div class="item">Fit</div>
    <div class="item">Fit</div>
    <div class="item">Fit</div>
  </div>
</div>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.1/css/all.min.css" integrity="sha512-KfkfwYDsLkIlwQp6LFnl8zNdLGxu9YAA1QvwINks4PhcElQSvqcyVLLD9aMhXd13uQjoXtEKNosOWaZqXgel0g==" crossorigin="anonymous" referrerpolicy="no-referrer" />

I hope someone has an answer to this using only JavaScript, and I hope no one flags this as a duplicate, as I am trying to not do duplicates.

Ruby algorithm for generating EChart Waterfall data

I’m trying to get this chart working.

EChart Sandbox: Waterfall Chart

And this the ruby code to elaborate my data.

    data = [ 500, 100, -1000, 300, 500]

    positive_values = []
    negative_values = []
    
    data.each_with_index do |value, index|
  
      if value.negative?
        positive_values << "-"
        negative_values << value.abs
      else
        positive_values << value
        negative_values << "-"
      end
  
    end

    base_values = []
  
    data.each_with_index do |value, index|

      base_values << 0 && next if index == 0

      base = base_values[index-1]

      base -= value.abs.to_f if value.negative?
      base += data[index-1].to_f if data[index-1].positive?

      base_values << base.round(2)

    end
  
    return { base_values: base_values, positive_values: positive_values, negative_values: negative_values }

Now this code works perfectly fine while you have positive values.

But when you start to have, as the code above, negative numbers that are going below 0, the algorithm doesn’t work, and I’m not able to understand the way to fix it.

The expected graph that i’m trying to get with the data mentioned above is the following.

Expected Graph – EChart

YAML/yamljs string deserialization behaviour

I was testing YAML (yamljs) with random inputs (please don’t ask why it’s a long story :D). I’m not very well versed in the YAML spec, but as far as I understand YAML should be able to serialize and deserialize primitives (strings, numbers, booleans) without an object or array wrapper. This however doesn’t always seem to be the case.

I isolated one failing case:

import YAML from 'yamljs'

describe('YAML', () => {
  it('should be equal to the input', () => {
    const str = '0xn5t'
    expect(YAML.parse(YAML.stringify(str))).toBe(str)
  })
})

Where it '0xn5t' is somehow parsed back to 5

Expected: "0xn5t"
Received: 5

Could someone please guide me to the spec where this behaviour is explained? Could this be an issue with the library I’m using?

Does anyone know why my form validation is not working in my upload component?

I am trying to allow a user to submit an image and a title for that image that gets sent to my backend API. I want a user to not be able to submit to that API if the title input box is empty. So I figured I need to implement a form validation for this. But for some reason, it is not working. Can someone help me figure out what I need to do to get it working so that the error displays when the title input is empty? I have a sandbox also if that helps. https://codesandbox.io/s/peaceful-frog-ui4413?file=/src/App.js

Upload.jsx:

import '../../components/pages/styles/Uploads.css';
import {Formik, Field, Form, ErrorMessage} from 'formik';
import * as Yup from 'yup';
import {useEffect, useState} from 'react';
import {} from 'react-router-dom';
import {useDispatch, useSelector} from 'react-redux';
import axios from 'axios';
import {clearMessage} from '../../slices/messages';
import authHeader from '../../services/auth-header';
const API_URL = 'http://localhost:8080/posts';

function Uploads() {
    const {user: currentUser} = useSelector((state) => state.auth);
    const [file, setFile] = useState();
    const [title, setTitle] = useState();
    const [description, setDescription] = useState('');
    const [loading, setLoading] = useState(false);
    const [content, setContent] = useState('');
    const [preview, setPreview] = useState(null);
    const initialValues = {
        title: '',
    };
    const [formValues, setFormValues] = useState(initialValues);
    const [formErrors, setFormErrors] = useState();

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

    const validate = (values) => {
        const errors = {};
        if (!values.title) {
            errors.title = 'Title of Post is required!';
        }
        return errors;
    };

    const handleChange = (e) => {
        const {name, value} = e.target;
        setFormValues({...formValues, [name]: value});
    };

    const handlePost = (formValue) => {};

    const onAddImage = (file) => {
        window.URL.revokeObjectURL(preview);
        if (!file) return;
        setPreview(window.URL.createObjectURL(file));
    };
    const postUserImage = async (event) => {
        //This is the code that will get passed to my backend. I need the image and title to be added here somehow.
        event.preventDefault();

        const formData = new FormData();
        formData.append('file', file);
        formData.append('title', formValues.title);

        const result = await axios.post('/post/upload', formData, {
            headers: {...authHeader(), 'Content-Type': 'multipart/form-data'},
        });
        console.log(result.data);
        setFormErrors(validate(formValues));
    };

    return (
        <div className='page'>
            <div className='upload-card'>
                <div id='preview'>
                    <img
                        src={preview || require('../../assets/user-solid.jpeg')}
                        id='image'
                        alt='Thumbnail'
                        className='user-post'
                    />
                </div>
            </div>
            <div className='upload-container'>
                <div className='post-form-container'>
                    <p id='upload-form-label'>Hello, feel free to post an image!</p>
                    <form
                        // onSubmit={'return Validate(this);'}

                        onSubmit={postUserImage}
                        className='upload-form'
                    >
                        <div className='panel'>
                            <div className='button_outer'>
                                <div className='btn_upload'>
                                    <input
                                        filename={file}
                                        onChange={(e) => onAddImage(e.target.files[0])}
                                        type='file'
                                        accept='.jpeg,.svg,.gif,.png'
                                        id='image-selection-btn'
                                    ></input>
                                    Choose your Art
                                </div>
                            </div>
                        </div>
                        <input
                            type='text'
                            className='form-control'
                            placeholder='Enter Title'
                            id='cred-input'
                            value={formValues.title}
                            onChange={handleChange}
                            initialValues={initialValues}
                        />

                        <button type='submit' id='post-upload-btn'>
                            Upload Image
                        </button>
                    </form>
                </div>
            </div>
        </div>
    );
}

export default Uploads;

A responsive Web-Server (Html page) to Handel HTTP request

I have some issues creating an Html page that reacts as a web server. Whit that I mean, there are other pages that send get/post requests every minute to this URL to add some content to this page. I want this webpage to be able to listen to any incoming HTTP request and show the new content on the page. Then from this webpage, everything will be written to a database. Is it even possible to do so?! And what are you recommending for such a process(Ajax, nod.js, …)?!
I have my Html page running on my server. I tried to reload the page with javascript every minute to collect the new get/post requests but I was not successful To make it work properly?!
I appreciate any hint?!!

Thanks

Edit Functionality React

import React, { useEffect, useState } from 'react'
import '../assets/css/popup.css';
import { IoIosCloseCircle } from "react-icons/io";
import axios from 'axios';
import {useParams } from 'react-router-dom';

const Edit= ({closeSuspenduser}) => {
  const [categories, setCategories] =  useState([]);
  const [data, setData] = useState ({
    title: "",
    serialnumber: "",
    price: "",
    category: "",
    description: "" 
  })

  const [profile, setProfile] = useState([]);
        const {assetId } = useParams();
    
  const getAssetProfile = (assetId) => {
      axios.get(`/assets/${assetId}`, {
          responseType: 'json'
      }).then(response => {
          if (response.status === 200) {
              console.log(response.data)
              setProfile(response.data)
          }
      })
  }
  useEffect(() => {
      if (assetId) {
          getAssetProfile(assetId);
      } 
  }, [assetId])

  function submit(e) {
    e.preventDefault();
    axios.put(`/assets/${assetId}`, {
      title: data.title,
      serialnumber: data.serialnumber,
      price: data.price,
      category: data.categorie_id,
      description: data.description
    })
    
    .then(res => {
      console.log(res.data)
      window.location.href = "../Assets";
    })
  }
  function handle(e) {
    const newdata ={ ...data }
    newdata[e.target.id] = e.target.value
    setData(newdata)
    console.log(newdata)
  }
             
  return(
    <div>
    <div className='popup'>
      <div className='popup-content'>
        <div className='popupheader'>
          <h3>EDIT ASSET</h3>
          <button className='close'onClick={() => closeSuspenduser(false)}>
            <IoIosCloseCircle size='2rem' color='var(--gray)' className='closebtn'/>
          </button>
        </div>
        <div className='popup-main'>
          <form onSubmit={(e) => submit(e)}>
            <div className='email'>
              <h4>ASSET NAME</h4>
              <input type='text' placeholder={profile.title} onChange={(e) => handle(e)} id="title" value={data.title}/>
            </div>
            <div className='username'>
              <h4>SERIAL NUMBER</h4>
              <input type='text' placeholder={profile.serialnumber} onChange={(e) => handle(e)} id="serialnumber" value={data.serialnumber}/>
            </div>
            <div className='password'>
              <h4>PRICE</h4>
              <input type='number' placeholder={profile.price} onChange={(e) => handle(e)} id="price" value={data.price}/>
            </div>
            <div className='password'>
              <h4>DATE PURCHASED</h4>
              <input type='date' onfocus="(this.type='date')" onblur="(this.type='text')" placeholder={profile.purchase_date} onChange={(e) => handle(e)} id="purchase_date" value={data.purchase_date}/>
            </div>
            <div className='assign-assets'>
              <h4>CATEGORY</h4>
              {/* <select>
                <option disabled selected value="">{profile.categorie[0].title}</option>
                {
              categories.map((val) => {
                return(
                <option onChange={(e) => handle(e)} id="category" value={data.category.}>{val.title}</option>
                                )})
                              }
              </select> */}
            </div>
            <div className='accessories'>
              <h4>DESCRIPTION</h4>
              <input type='text' placeholder={profile.description} onChange={(e) => handle(e)} id="description" value={data.description}/>
            </div>
            <button className='createuser'>
              SAVE EDITS
            </button>
          </form>
        </div>
      </div>
    </div>
    </div>
  )
}
          export default Edit;

this is an edit popup; I am trying to view the previous data information in the input so as to edit.
Also while editing a specific input, I am losing all the previous data …
How do I retain the previous information after editing so I can save all of them instead of re-editing every input in the form

I manage to upload the image but on the firebase storage but it says undefined

I cant preview the image inside the store, it says undefined I manage to upload it on images/ folder but the name of the file is undefined instead of the actual name of the image

enter image description here

const uploadFile = () => {



  console.log(selectedImages);
  const storageRef = ref(storage, 'images/' + selectedImages.name);

  const uploadTask = uploadBytesResumable(storageRef, selectedImages, metadata);
  console.log(selectedImages);

  uploadTask.on('state_changed',
    (snapshot) => {

      const progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
      console.log(progress);
      console.log('Upload is ' + progress + '% done');
      switch (snapshot.state) {
        case 'paused':
          console.log('Upload is paused');
          break;
        case 'running':
          console.log('Upload is running');
          break;
        default:
          break;
      }
    },
    (error) => {
      console.log(error);
    },
    () => {
      // Upload completed successfully, now we can get the download URL
      getDownloadURL(uploadTask.snapshot.ref).then((downloadURL) => {
        console.log('File available at', downloadURL);
      });
    }
  );

};