React Native “View config getter callback for component ‘input’ must be a function” and “Text strings must be rendered within component” mobile

I’m making a react native app where the user will push a button (displayed via the render buttons function) and then a modal will pop up containing a form, creating using react hook form. All of this works on the web testing, but when testing on an actual phone (ios), I get an error saying Text strings must be rendered within a <Text> component
enter image description here
As well as this other invariant violation error:
enter image description here

My code is as follows:

import React, {useState, useEffect} from 'react';
import { View, Text, Button, Alert, Modal, Pressable, TextInput } from 'react-native';
import { globalStyles } from '../styles/global';
import { useForm } from "react-hook-form";

export default function IngredientScreen({ navigation }) {
    const [modalVisible, setModalVisible, modal2Visible] = useState(false);
    const [text, setText] = useState(' ');
    const { watch, formState: { errors } } = useForm();
    const [ingredientsPair, setIngredientPair] = useState({ingredient: "", category: "", delete: ""});
    const { register, handleSubmit,  reset } = useForm({
      defaultValues: ingredientsPair,
    });

    //List out ingredients with categories? Prepopulated for now
    var ingredientList = [
        {
            category: "Cooking & Baking Ingredients",
            items: ["Flour"]
        },
        {
            category: "Dips & Spreads",
            items: ["Cream Cheese"]
        },
        {
            category: "Fresh & Frozen Fruits",
            items: ["Passion Fruit", "Apples"]
        },
        {
            category: "Grains, Rice & Cereal",
            items: ["Millet"]
        },
    ];
    
    function RenderButtons() {
      return ingredientList.map(buttonInfo => (
        <>
          <Text >{buttonInfo.category}</Text>
          {buttonInfo.items.map((item) => {
            var orginalIngredient = item;
            return (
              <View>
                  <Modal
                    animationType="slide"
                    transparent={true}
                    visible={modalVisible}
                    onRequestClose={() => {
                      Alert.alert("Modal has been closed.");
                      setModalVisible(!modalVisible);
                    }}
                  >
                    <View style={globalStyles.centeredView}>
                      <View style={globalStyles.modalView}>
                        <form onSubmit={handleSubmit(editIngredient)}>
                          <label style={{fontSize: 12, fontWeight: 'bold', color: '#333', fontFamily: 'raleway-bold',}}>
                            Are you deleting this ingredient?
                          </label>
                          <select {...register("delete")} style={{width: 70}}>
                            <option value="Yes">Yes</option>
                            <option value="No">No</option>
                          </select>
                          <Text>{'n'}</Text>
                          <Text style={globalStyles.h6}>Edit your ingredient here</Text>
                          <input 
                            {...register("ingredient")} 
                            placeholder="Input your ingredient"
                          />
                          <select {...register("category")}>
                            <option value="Condiments & Sauces">Condiments & Sauces</option>
                            <option value="Cooking & Baking Ingredients">Cooking & Baking Ingredients</option>
                            <option value="Dips & Spreads">Dips & Spreads</option>
                            <option value="Fresh & Frozen Fruits">Fresh & Frozen Fruits</option>
                            <option value="Fresh & Frozen Vegetables">Fresh & Frozen Vegetables</option>
                            <option value="Grains, Rice & Cereal">Grains, Rice & Cereal</option>
                          </select>
                          <Pressable
                          style={[globalStyles.button, globalStyles.buttonClose]}
                          onPress={handleSubmit(editIngredient)}
                          type="submit"
                          >
                            <Text style={globalStyles.buttonText}>Submit</Text>
                          </Pressable>
                        </form>
                      </View>
                    </View>
                  </Modal>
                  <Pressable
                    style={[globalStyles.button, globalStyles.buttonOpen]}
                    onPress={() => {setModalVisible(true)}
                  >
                    <Text style={globalStyles.buttonText} key={item}>{item}</Text>
                  </Pressable>
                </View>
            );
          })}
        </>
      ));
    }

    const editIngredient = (data) => {
      setModalVisible(!modalVisible)
      ingredientList.forEach(item => {
        if (data.category == item.category) {
          for (var i=0; i < item.items.length; i++) {
            if (data.ingredient == item.items[i]) {
              if (data.delete == "Yes") {
                //Change to connect with users
                item.items.splice(i,1);
                alert(item.items);
                break
              } else {
                //edit ingredient
                break
              }
            }
          }
        }
      })

    };

    //Button must be able to select category as well
    return (
      <View style={globalStyles.container}>
        <Text style={globalStyles.h1}>Your Ingredients</Text>
        <View>
          { RenderButtons() }
        </View>
      </View>
    );
};

When I changed all the <Text> components in the form to <label>, I still got the error about text rendering, and I’m not sure where the invariant violation error comes from.
Any help would be much appreciated!

Looking for a function that takes an Array, a path, and a value, and returns the indexes of the array where the value matches the path

What I am looking for, is a function called findIndexes that takes an array, and a path. and the function will traverse the path in that array and return all the indexes of the rows array if the address includes “S St”.

var data = {
  rows: [
    {
      id: 1,
      address: "1 S St",
    },
    {
      id: 2,
      address: "1 S St",
    },
    {
      items: [{ id: 1, address: "1 S St" }],
    },
  ],
};

findIndexes(data.rows, "rows[].items[].address", "S St"); //Returns [2]
findIndexes(data.rows, "rows[].address", "S St"); //returns [0,1]

Uncaught TypeError: Cannot read properties of undefined (reading ‘companyName’) JS Objects

i have a problem about when i trying mapping my data. I want a reach company name in supplier in products. How can i fix it?

{products.map((repo) => (
      <div
        style={{
          backgroundColor: "#c1d3d4",
          marginTop: 50,
          display: "flex",
          flexDirection: "column",
          minWidth: 1000,
          paddingLeft: 50,
          marginLeft: 400,
          paddingRight: 30,
          paddingBottom: 12,
          borderRadius: 15,
        }}
        span={24}
      >
        <p style={{ flex: 1, fontWeight: "bold", fontSize: 26 }}>
          {repo.name}
        </p>

        <p style={{ fontWeight: "bold", fontSize: 14 }}>{repo.supplier.companyName}</p>

        <p style={{ fontWeight: "bold", fontSize: 14 }}>
          {repo.quantityPerUnit}
        </p>
        <div
          style={{
            display: "flex",
            flexDirection: "row",
            justifyContent: "space-between",
            alignContent: "flex-end",
          }}
        >
          <p
            style={{
              fontSize: 20,
              fontWeight: "800",
              color: "green",
              alignSelf: "flex-end",
            }}
          >
            {repo.unitPrice.toFixed(2)}
          </p>
          <Button type="primary" onClick={() => AddCart(repo)}>
            Sepete Ekle
          </Button>
        </div>
      </div>
    ))}

this is error message
error

this is data:

https://northwind.vercel.app/api/products

Nightwatch JS | Getting Next Child Text

I am attempting to write a function that can acquire the text value of a nextChild node underneath a label bracket. I need to be able to put that text into a global variable that I can reference later in the test, but my current function, while it is retrieving the webElementId, is not retrieving the text. Instead, my console.log function is outputting a blank value.

To give some context on the code in question, here is the HTML layout of the field I am attempting to parse.

<iframe> id=[some_id]
  #document
    <html>
      <head>
        <body>
          <div> id=[some_id]
            <form> id=[some_id]
              <div> id=[some_id]
                <div> id=[some_id]
                  <div> style=[some_style]
                    <label>[some text]<label>
                      [text field in question]

That’s just the basic layout, but here is the code snippet that I am attempting to use to grab the sibling node, get the id, and then get the text of the webElementId.

.getNextSibling('div[id=popover_content] > form[id=perform_sub_task_form] > div[id=perform_task] > div[id=dialog_container] > div > label:nth-of-type(8)', function(dateObj) {
  let dateVal = dateObj.value.getId()
    console.log(`datevalue: ${dateVal}`)
    browser.elementIdText(`${dateVal}`, function(result) {
      console.log('n' + result.value)
      initial_date = result.value
})
 })

I have already attempted to simplify this and run a callback function on just the .getNextSibling function using result.value.getText(), that just results in Nightwatch telling me that the function doesn’t exist. Reading the documentation for the getNextSibling() function, I found that getId() can be added onto the callback, so I decided to use that to my advantage and attempt to use the provided webElementId and write the snippet above.

My question is, how can I edit this snippet above so that it stops giving me a blank value? Is there an issue with my browser.elementIdText() function?

Store html in database in django

Hello I’m trying to store HTML code in the database with Django but facing a problem with escape characters.

here’s an object that I’m trying to store but

{
   "data": "<div class="read" id="search">Google</div>"
}

here’s what I’m getting in database.

<div class="read" id="search">Google</div>

I tried to store with Model.objects.create()

this becomes a problem to parse too much HTML in javascript then. JSON object gets confused with the double-quotes. the solution is I want to store data in database with backslashes as well so it can be parsed correctly as a JSON object.

How to load localStorage value using fetch() on page load?

I have 2 html pages, index.html and dropdown-component.html

onclick of a button in index.html, I try to fetch the content of dropdown-component.html

Using the ff:

function fetchJXSelectMenu() {
fetch('dropdown-component.html')
    .then(response => response.text())
    .then(text => document.querySelector('#component-assist-jx-select-menu').innerHTML = text);
}

It is loaded in a div <div id="component-assist-jx-select-menu"></div>.

The problem is, the “component” it loads is a select/option that utilizes localStorage to remember the last selected option of the user.

It looks like this:

$(function () {
    $('#AssistSelectMenu').change(function () {
        localStorage.setItem('JXselect', this.value);
    });
    if (localStorage.getItem('JXselect')) {
        $('#AssistSelectMenu').val(localStorage.getItem('JXselect'));
    }
});

If I’m not using the fetch() method, the localStorage function works fine, but if I do use it, it fails to load the last selected option of the user on page load. I’m guessing this is because the browser has already finished rendering the page and can’t process the localStorage for the newly loaded component.

So my question is how do I workaround this? I tried putting the script in the component but that didn’t solve it at all.

Thank you in advance for any help!

How to use google earth engine chart in jupyter notebook

Import ee
Import ipygee as ui


try:
        ee.Initialize()
except Exception as e:
        ee.Authenticate()
        ee.Initialize()


   
#chart_ts.renderWidget()  # for Jupyter Notebook or Lab

CHIRPS = ee.ImageCollection('UCSB-CHG/CHIRPS/PENTAD')


region = ee.FeatureCollection("users/hrishippatel/IndiaStates").filterMetadata('NAME_1', 'equals','Gujrat')
precip = CHIRPS.filterDate('2016-01-01', '2019-12-31')
GujaratPrecip = precip.sum().clip(region).multiply(0.25)
#Map.addLayer(GujaratPrecip, {'min': 0, 'max': 1000, 'palette':"f6ffa9,1fe2b5,1da0fd,2b7bf3,141899"},'Long-term Rainfall')

Chart.image.series(precip, region, ee.Reducer.mean(),1000, 'system:time_start').setOptions({
          title: 'Precipitation Full Time Series',
          vAxis: {title: 'mm/pentad'},
});

Error
:

NameError                                 Traceback (most recent call last)
Input In [3], in <cell line: 23>()
     20 GujaratPrecip = precip.sum().clip(region).multiply(0.25)
     21 #Map.addLayer(GujaratPrecip, {'min': 0, 'max': 1000, 'palette':"f6ffa9,1fe2b5,1da0fd,2b7bf3,141899"},'Long-term Rainfall')
---> 23 Chart.image.series(precip, region, ee.Reducer.mean(),1000, 'system:time_start').setOptions({
     24           title: 'Precipitation Full Time Series',
     25           vAxis: {title: 'mm/pentad'},
     26 })

NameError: name 'Chart' is not defined

​
​
​
​

Regex to capture string between string into array in js

If we have the following string:

"hukhkhknClosing Date: Friday 22nd April 2022nwdwqdwqdwqdnClosing Date: Friday 22nd April 2023newdewfewf"

and we want to get the 2 dates from it "Friday 22nd April 2022" and "Friday 22nd April 2023"

how do I go about getting an array back of all captured strings using js.

[ "Friday 22nd April 2022", "Friday 22nd April 2023" ]

There is an issue in my regex but not sure how to fix it so that it doesn’t match everything in between the first n it finds:

(?<=Closing Date:s)(.*)(?=\n)

https://regexr.com/6k2uf

The js I tried is this:

var reg = new RegExp('(?<=Closing Date: )(.*)(?=\n)/g');
reg.exec("hukhkhknClosing Date: Friday 22nd April 2022nwdwqdwqdwqdnClosing Date: Friday 22nd April 2023newdewfewf")

how can i make stars move one by one and form an outline of a circle in the center of the page

i have this code i want to move the stars one by one from the right side and form an outline of a circle in the center

.stars {
      --num: 10;
      /* the number of stars */
      --w: 50vmin;
      width: var(--w);
      aspect-ratio: 1 / 1;
      position: relative;
      left: 100%;
      /* out of view to start with */
      transition: left 2s;
    }

    .stars.show {
      left: 0;
    }

    .stars>* {
      --starw: calc(var(--w) / var(--num));
      width: var(--starw);
      height: 50%;
      top: 0;
      left: calc(50% - (var(--starw) / 2));
      transform: rotate(calc(var(--n) / var(--num) * 360deg));
      transform-origin: 50% bottom;
      position: absolute;
      text-align: center;
    }

    .stars>*::after {
      content: '★';
      position: absolute;
      top: 0;
      text-align: center;
      z-index: 1;
      width: 100%;
      left: 0;
      font-size: var(--starw);
      color: #FFD700;
      font-size: 1.5rem;
    }

    .stars *:nth-child(1) {
      --n: 1;
    }

    .stars *:nth-child(2) {
      --n: 2;
    }

    .stars *:nth-child(3) {
      --n: 3;
    }

    .stars *:nth-child(4) {
      --n: 4;
    }

    .stars *:nth-child(5) {
      --n: 5;
    }

    .stars *:nth-child(6) {
      --n: 6;
    }

    .stars *:nth-child(7) {
      --n: 7;
    }

    .stars *:nth-child(8) {
      --n: 8;
    }

    .stars *:nth-child(9) {
      --n: 9;
    }

    .stars *:nth-child(10) {
      --n: 10;
    }
  <button onclick="document.querySelector('.stars').classList.add('show');">CLICK ME</button>
    <div class="stars">
      <div></div>
      <div></div>
      <div></div>
      <div></div>
      <div></div>
      <div></div>
      <div></div>
      <div></div>
      <div></div>
      <div></div>
    </div>

i have this code i want to move the stars one by one from the right side and form an outline of a circle in the center, i have this code i want to move the stars one by one from the right side and form an outline of a circle in the center

append HTML Blob data to DOM

I use the following JavaScript to get a Blob object from the clipboard

const clipboardItems = await navigator.clipboard.read()
const clipboardItem = clipboardItems[0]
const content = await clipboardItem.getType('text/html')

The content variable is a Blob object of type ‘text/html’. How do I append the content of this Blob to the DOM e.g. show the content of this blob as the inner HTML of the element

<div id="blob-content"></div>

Click a button when the page reloads

When I click a button (#test-element) it makes the page refresh but I want it to then run a function after the page is refreshed to open the cart by clicking a button automatically(.cart-contents). How do I run a function after the page is refreshed if the add to cart button (#test-element) was clicked. So the page refreshes and clicks another button(.cart-contents)?

<script>
 $("#test-element").on("click",function() {
 setTimeout(function () {
 location.reload(true);
 }, 500);
 });
</script> 
<script type="text/javascript">
  $("#test-element").on("click",function() {
  setTimeout(function () {  
  $(document).ready(function(){
  $(".cart-contents").trigger('click'); 
  }, 500);
  });});
</script>

Rewriting regular function to arrow function caused an erroe | Cannot access ‘getWorkStatesFilterIDs’ before initialization

I’m trying to rewrite a regular function to an arrow function and got an error saying ReferenceError: Cannot access 'getWorkStatesFilterIDs' before initialization

 function getWorkStatesFilterIDs(workStatesToFilterBy, params) {
    let ids = [];
    for (const _state of workStatesToFilterBy) {
      if (Object.keys(params).includes(_state.key)) {
        let state_id = WorkflowStates.findOne({title: _state.title})._id;
        ids.push(state_id);
      }
    }
    return ids;
  }

  function getFilterQuery() {
    let finalQuery = {
      archived: false,
      boardId: {$in: boardIds},
      listId: {$nin: [...managerListIds, ...unreportedListIds]},
      createdAt: dateFilterQuery(),
    };

    let workStatesToFilterBy = [
      {key: 'inProgress', title: 'In Progress'},
      {key: 'completed', title: 'Completed'},
      {key: 'identified', title: 'Identified'},
    ];
    if (params.completed || params.inProgress || params.identified) {
      finalQuery = {
        ...finalQuery,
        workflowStateId: {
          $in: getWorkStatesFilterIDs(workStatesToFilterBy, params),
        },
      };
    }
    return finalQuery;
  }

This works the way I expect, but when I change getWorkStatesFilterIDs function to arrow function, I got the error.

    const getWorkStatesFilterIDs = (workStatesToFilterBy, params) => {
      let ids = [];
      for (const _state of workStatesToFilterBy) {
        if (Object.keys(params).includes(_state.key)) {
          let state_id = WorkflowStates.findOne({title: _state.title})._id; //find the key for the filter condition
          ids.push(state_id);
        }
      }
      return ids;
    };

  function getFilterQuery() {
    let finalQuery = {
      archived: false,
      boardId: {$in: boardIds},
      listId: {$nin: [...managerListIds, ...unreportedListIds]},
      createdAt: dateFilterQuery(),
    };

    let workStatesToFilterBy = [
      {key: 'inProgress', title: 'In Progress'},
      {key: 'completed', title: 'Completed'},
      {key: 'identified', title: 'Identified'},
    ];
    if (params.completed || params.inProgress || params.identified) {
      finalQuery = {
        ...finalQuery,
        workflowStateId: {
          $in: getWorkStatesFilterIDs(workStatesToFilterBy, params),
        },
      };
    }
    return finalQuery;
  }

I thought I had to switch the order getWorkStatesFilterIDs function to getFilterQuery function, but got the same error.

I changed both getFilterQuery and getFilterQuery function to arrow function, but also got the same error.

Does anybody know how can I change getWorkStatesFilterIDs function to arrow one?

Check object items length

I am working currently on a filter bar. Using react-hook-form {useForm}.
What I try to achieve as I console.log(watch()) I get back and array of the filter form items,
I can see it contains my filter items all cool. I have dates as string and autocomplete fields as array.
On to the point I have a defaultValues object with all field empty, so no default filter. I want to compare defaultValues (which is empty fields) with watch items, so if I have active filters I want to count them and give back the number in the filter bar as a number.

Could you please help me how to compare them and also count if watch() item not empty, null or undefined than increase count.

export const defaultValues = {
id: [],
dateFrom: '',
dateTo: '',
numbers: [],
cars: [],
}

console.log(wathc()) response:

{id: Array(2), dateTo: "2022-04-31T00:00:00.000Z", dateFrom: "", cars: Array(0), numbers: Array(0)}

One of the array has 2 items, and one of is not an empty string. I want to count them up and in the Filter Bar (3) so that we have 3 active filter.