Add line break to .js data file in react

Hi i have a js file which is exporting data to my components how do i make some of the text bold and force a line break? I’ve tried n but that doesn’t work. I’ve annotated where i want the line break and where i want the text to be bold.

export const productData = [
    ...
        desc: "{bold} Heavy on features.Light on price. {line break here} Stay connected. Even without your phone. With powerful features to help keep you connected, active, healthy and safe, Apple Watch SE is a lot of watch for less.",

]

While using useState hook and onClick event in react I get error when calling the function in onClick event

import React,{useState} from ‘react’;

export function App(props) {
const [fruit, setFruit ] = useState(“apple”)

  function settingFruit_1()
  {
    setFruit("mango");
  }

  return ( 
    <div className='App'>
      <h1>{fruit}</h1>
      //why am I getting the error when calling the function like this onClick = {settingFruit_1()}
      <button onClick = {settingFruit_1()}> submit </button> 
      
    </div>
  );
}


Here is the error that I see:
Error: Too many re-renders. React limits the number of renders to prevent an infinite loop.
    at renderWithHooks (<anonymous>:11510:25)
    at mountIndeterminateComponent (<anonymous>:14733:23)
    at beginWork (<anonymous>:15659:24)
    at HTMLUnknownElement.callCallback2 (<anonymous>:3454:24)
    at Object.invokeGuardedCallbackDev (<anonymous>:3479:26)
    at invokeGuardedCallback (<anonymous>:3513:41)
    at beginWork$1 (<anonymous>:18904:17)
    at performUnitOfWork (<anonymous>:18371:22)
    at workLoopSync (<anonymous>:18308:15)

Wait for the reading of a csv file

I’m trying to read a csv file in Typescript with “csv-parse” library by creating an observable; the following code use fs.createReadStream to read the file; I would like to return the observable and subscribe to it, but the process does not get nothing, probably because I’m not waiting the asynchronous fs.createReadStream; how to resolve?

export function createCsvObservable(
  filePath: string,
  fileType: string | undefined = undefined,
  fieldDelimiter: string = ",",
  columnHeader: boolean = true
) {
  if (fileType !== "csv") {
    throw Error(`Cannot create CSV observable from non CSV file`);
  }

  const log = logs.extendLogger(
    _log,
    "Create csv observable from csv file",
    createCsvObservable
  );

  log.info(`***`);

  return new Observable<StdJsonDoc>((subscriber) => {
    const parser = fs.createReadStream(filePath).pipe(
      parse({
        delimiter: fieldDelimiter,
        columns: columnHeader,
        trim: true,
        skip_empty_lines: true,
        relax_column_count: true,
      })
    );

    parser.on("readable", () => {
      let record: StdJsonDoc;
      while ((record = parser.read())) {
        subscriber.next(record);
      }
    });
    parser.on("end", () => {
      subscriber.complete();
    });
    parser.on("error", (err) => {
      log.error(
        {
          file: filePath,
        },
        `Parser error: ${err.message}`
      );
      subscriber.error();
    });
  });
}

The caller run:

const myObservableCsv = createCsvObservable(
    path.join(__dirname, "data", "myCsvFile.csv"),
    "csv"
  );

convert Class component into Functional component in React

I have been studying React with functional component

one day, I had been asked to convert this class component into a functional component

it was too confusing since I have no experience in the class component.

please help me to solve the code below.

import React, { PureComponent } from 'react';

const getWidth = () => window.innerWidth;

class Component extends PureComponent {
   static defaultProps = {
   callback: (width) => {}, 
   children: null,
   text: 'Confirm'
   };

componentDidMount() {
   window.document.body.addEventListener('resize', this.resize);
}

componentWillUnmount() {
   window.document.body.removeEventListener('resize', this.resize);
}

resize = (ev) => {
   const { callback } = this.props;
   callback(getWidth());
};

render() {
   const { callback, children, text } = this.props;


return (
  <>
    <div>{children}</div>
    <button onClick={callback}>{text}</button>
  </>
);

}
}

export default Component;

HTTP function times out when subscribing an FCM token to a topic in Cloud Function

Minimum reproducible code:

index.ts:

import * as admin from "firebase-admin"
import fetch, { Headers } from "node-fetch";

interface BarPayload {
  topic: string,
  token: string,
}

exports.bar = functions.https.onCall(async (data, context) => {
  if (data != null) {
    const payload: BarPayload = {
      topic: data.topic,
      token: data.token,
    }

    const url = `https://${location}-${project}.cloudfunctions.net/subscribeToTopic`
    await fetch(url, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        topic: payload.topic,
        token: payload.token,
      }),
    })
  }
  return null;
});

export const subscribeToTopic = functions.https.onRequest(async (req, res) => {
  const payload = req.body as BarPayload;
  fetch('https://iid.googleapis.com/iid/v1/' + payload.token + '/rel/topics/' + payload.topic, {
    method: 'POST',
    headers: new Headers({
      'Authorization': 'key=AA...Wp9',
      'Content-Type': 'application/json'
    })
  }).then(response => {
    if (response.status < 200 || response.status >= 400) {
      res.sendStatus(299)
    }
  }).catch(error => {
    console.error(error);
    res.sendStatus(299)
  })
  return Promise.resolve();
})

I’m running bar in Flutter and I see the timeout error in Logs Explorer:

textPayload: “Function execution took 60051 ms. Finished with status: timeout”


But if I change my subscribeToTopic from HTTP function to a callable function, then it works fine. For example:

exports.subscribeToTopic = functions.https.onCall(async (data, context) => {
  fetch('https://iid.googleapis.com/iid/v1/' + data.token + '/rel/topics/' + data.topic, {
    method: 'POST',
    headers: new Headers({
      'Authorization': 'key=AA...Wp9',
      'Content-Type': 'application/json'
    })
  }).then(response => {
    if (response.status < 200 || response.status >= 400) {
      console.log('Error = ' + response.error);
    }
  }).catch(error => {
    console.error(error);
  })
  return null;
});

(I know I’m making some trivial mistake, and I’m new to Typescript. Any help would be appreciated 🙂

AgGrid – change filter source code or user

Is it possible to recognise source of change filter for column.
Changes can be done manually by user or can be set by setFilterModel on gridApi project. The last method invoke onFilterChanged method

Method onFilterChanged takes one parameter type of FilterChangedEvent, can I find in this object information about source of changes?

Check updated state of GET request in useEffect Hook

When I create an item and click save, I would like when I return to the page it automatically updates with what I just created. So that my useEffect detects the changes that have just arrived at the level of the GET request.

But I tried everything, I tried to put the variable garden in the array of useEffect but it makes an infinite loop of GET request, I also tried to put setGarden it does not make an infinite loop but it does not update automatically, I have to reload the page…

Here is the code :

const [garden, setGarden] = useState([]);
const [plot, setPlot] = useState([]);
const [loading, setLoading] = useState(false);
const navigation = useNavigation();

  const gardenData = async () => {
    setLoading(true);
    const user = await AsyncStorage.getItem('user');
    const parsedUserData = JSON.parse(user);
    try {
      const response = await axios.get(
        `http://127.0.0.1/api/garden?user=${parsedUserData.user.id}`,
        {
          headers: {
            Authorization: `Token ${parsedUserData.token}`,
          },
        },
      );
      if (response.status === 200) {
        navigation.navigate('LogScreen');
        setGarden(response.data);
        setLoading(false);
        try {
          const plotResponse = await axios.get(
            `http://127.0.0.1/api/plots?garden=${response.data[0].id}`,
            {
              headers: {
                Authorization: `Token ${parsedUserData.token}`,
              },
            },
          );
          if (plotResponse.status === 200) {
            setPlot(plotResponse.data);
          }
        } catch (e) {
          alert(e);
        }
      }
    } catch (e) {
      console.log('Erreur ' + e);
      setLoading(false);
    }
  };

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

Thanks for the help !

Opening new tab based on Javascript output (broken code)

I’m making a hosting site, and I am trying to have a form where you can search a domain from a form. Check out the pseudocode to understand what I’m trying to do.

User types domain/search in box -> Presses DONE -> Opens new tab with the below format (with the user’s query)

https://example.com/cart.php?a=add&domain=register&query=QUERY_HERE

Here’s my code, but when the form submission, it searches domain=example.com (if I put example.com in the search box). What did I do wrong?

JavaScript (with JQuery):

$('.done').on('click', function() {

    var dataArray = $('#message').serializeArray();
  
    window.open('https://billing.zapprhosting.com/cart.php?a=add&domain=register&query=' + $.param( dataArray ));
  
  });

HTML Form:

<form id="message" target="_blank">
    <input id="domain-text" type="text" name="domain" placeholder="Write your domain name here.." />
</form>
<div class="button-center done">
     <a href="#"><p>SUBMIT</p></a>
</div>

webpack – export all folders with html inside

How i can export all my .html files and folders in .dist folder?

enter image description here

I use this script in webpack.config.js, but it doesn’t work with files in folders.

function generateHtmlPlugins(templateDir) {
  const templateFiles = fs.readdirSync(path.resolve(__dirname, templateDir));
  return templateFiles.map(item => {
    const parts = item.split('.');
    const name = parts[0];
    const extension = parts[1];
    return new HTMLWebpackPlugin({
      filename: `${name}.html`,
      template: path.resolve(__dirname, `${templateDir}/${name}.${extension}`),
      inject: false,
    })
  })
}

const htmlPlugins = generateHtmlPlugins(environment.paths.src.html)

calculate object in array by if condition app script

I’m using app script to get data from API and return array JSON:

var jsn = [
  { numbers: '228', id: '4152', gendar: 'female' type: 'femalemale', num: '20'},
  { numbers: '356', id: '4152', gendar: 'female' type: 'femalemale', num: '10'},
  { numbers: '978', id: '8479', gendar: 'male' type: 'malefemale', num: '15'},
  { numbers: '101', id: '8479', gendar: 'male' type: 'malefemale', num: '12'},
];

var obj = {};
for (let o of jsn) {
  try {
    try {
obj[o.id].numbers.push(o.numbers)
obj[o.id].num.push(o.num)
} catch (e) {
obj[o.id].numbers = [o.numbers]
obj[o.id].num= [o.num]
}
  } catch (e) {
    o.numbers = [o.numbers];
    o.numbers = [o.num];
    obj[o.id] = o;
  }
}

var arr = Object.values(obj);
console.log(arr);

this code get result:

  [{ numbers: 292, id: '4152', gendar: 'female', num: 30 },
  { numbers: 539.5, id: '8479', gendar: 'male', num: 27 }]

I want IF ‘gendar’ has word exit in first word in ‘type’ then calculate ‘numbers’.
exemple IF ‘female’ in gendar, exit in first word in word ‘femalemale’ in type calculate numbers as math: numbers – num. mean 292 – 30 = 262.

the result maybe like :

[{ numbers: 262, id: '4152', gendar: 'female', num: 30},
      { numbers: 539.5, id: '8479', gendar: 'male', num: 27 }]

And IF ‘female’ in gendar, exit in last word in word ‘malefemale’ in type calculate numbers as math: numbers + num . mean 539.5 + 27 = 566.5.

the result maybe like :

[{ numbers: 292, id: '4152', gendar: 'female', num: 30},
      { numbers: 566.5, id: '8479', gendar: 'male', num: 27 }]

I try this code : for (let id in obj) if (obj[id].gendar (string.match(/^type/g))) obj[id].numbers - obj[id].num;

if this method true is change array to string but I don’t want array change to string . I want keep it as object.
this code give me error: TypeError: obj[id].gendar is not a function.

note: use it but without change the type of array to string. keep it as object.

how to get list of product under category in vue js

hello i’m new to vue and
i have a list of json data which has a list of products under category, please how do i get to display a product under each category

here’s my json data for the category array

{
    "_id": "62566ec30e42d6c5ab370e7c",
    "products": [],
    "type": "mobile phone",
    "__v": 0
}

my product array

{
    "_id": "625671db370e769a8a93a510",
    "reviews": [],
    "owner": {
        "_id": "6220db7ee861f3dbbaf21e3d",
        "name": "mr jacob",
        "about": "hello",
        "__v": 0
    },
    "category": {
        "_id": "62566ec30e42d6c5ab370e7c",
        "products": [],
        "type": "mobile phone",
        "__v": 0
    },
    "title": "galaxy s21",
    "description": "Lorem ipsum dolor sit amet consectetur adipisicing elit. Natus ullam iusto culpa assumenda enim ea, asperiores omnis, facere quos animi doloremque, architecto facilis aut? Nobis ab sit iusto praesentium quia.",
    "photo": "https://ajibade.s3.amazonaws.com/1649832365317",
    "price": 500,
    "stockQuantity": 1,
    "__v": 0,
    "id": "625671db370e769a8a93a510"
}

my html template to get the list of category in my data base

<div class="container" v-for="category in categories" :value="category._id" :key="category._id">
      <span>{{category.type}}</span>
    </div>

my script tag

<script>
export default {
  name: "Products",
  name: "categories",
  data() {
    return {
      categoryID: null,
      categories: [],
      products: [],
     
    };
  },

 
  mounted() {
    axios.get("http://localhost:5000/api/products").then(res => {
      console.log(res);

      this.products = res.data.products;
    });
    axios.get("http://localhost:5000/api/categories").then(res => {
      console.log(res);

      this.categories = res.data.categories;
    });
  }
};
</script>

please how do i filter the products and get it under a specific category, i’m lost

javascript: How use CompressionStream(‘gzip’) for a file from ?

I want compress a selected file from <input type="file"> and download it using native CompressionStream (actually work only on Chrome)

async function compress(input) {
  const file = input.files[0];
  const rs = file.stream().pipeThrough(new CompressionStream('gzip'));
  const blob = await new Response(rs).blob();
  const url = window.URL.createObjectURL(blob);
  window.open( url );
}
<input type="file" id="file" onchange="compress(this)">

Browser display the binary data instead of download…

UseReducer dispatch function throws unexpected error: Expected 0 arguments, but got 1

Couldn’t find any related answer, the only one was related to Redux directly, thus asking a question that may seem obvious to some of you.
As far as my code it seems that everything is correct yet I’m struggling with the following error: Expected 0 arguments, but got 1

Code:

 // An enum with all the types of actions to use in our reducer
  enum ActionType {
    INCREASE = 'INCREASE',
  }

  // An interface for our actions
interface Action {
  types: ActionType;
  payload: number;
}

// An interface for our state
interface allState {
  playersNumber: number,
  playerData: string
}


const reducer : any = (state : allState, action : Action) => {
    switch (action.types) {
      case ActionType.INCREASE:
        return { playersNumber: state.playersNumber + 5}
    }
  }

  const initialState = {
    playersNumber : 0,
    playerData: ""
  }

const App : FC<any> = () => {
  const [responseData , setResponseData] = useState<Array<object>>([]);

  const [state, dispatch] = useReducer(reducer, initialState);


  // Fetching data with Axios
  const fetchingData = async () => {
    const response = await axios.get<Array<object>>('http://localhost:3006/lfy');
    setResponseData(response.data);
    console.log(response.data.length);
    dispatch({type: ActionType.INCREASE})
    
  }

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


  return (
    <Routes>
      {console.log(state)}
      <Route path="/" element={<Home />} />
    </Routes>
  );
}

export default App;

JavaScript Get Array value [duplicate]

                const q = query(collection(db, "user"), where("StudentID", "==", StudentID));
                    let user = [];

                    getDocs(q).then(docSnap => {
                        docSnap.forEach((doc) => {
                            user.push({ ...doc.data(), id: doc.id })
                        });

                    });
                

                **console.log(user);**
                let A = user[0]['StudentID'];
                console.log(A);
                console.log(user[0]['StudentID']);

                if (user) {
                    console.log(user);
                    document.getElementById('errormessage').style.display = "none";
                    //User exist in the system
                    var table = document.getElementById('tablebody'),
                        newRow = table.insertRow(table.length),
                        cell1 = newRow.insertCell(0),
                        cell2 = newRow.insertCell(1),
                        cell3 = newRow.insertCell(2);

                    //Store Data to the Table Row
                    cell1.innerHTML = user[0].StudentID;
                    cell2.innerHTML = user[0].UserName;
                    cell3.innerHTML = TopUpAmount;

The highlighted console on the first line is able to get the user result as below. But I unable to get the user information by using let A = user[0][‘StudentID’]. Is there any way to get value from the array? Thanks Guys!
Console Result(console.log(user);) as below

[]
0: {Amount: 0, UserName: 'MAH KHAI KEAT', PaymentPassword: '120401', Email: '[email protected]', StudentID: 'i20018673', …}
length: 1
[[Prototype]]: Array(0)