Remove items from an array in order until matching item is found

I have an array of items

const test = [
  {
    id: '1',
  },
  {
    id: 'a',
  },
  {
    id: '3',
  },
  {
    id: 'b',
  },
  {
    id: '5',
  },
  {
    id: 'c',
  },
  {
    id: '7',
  },
];

These objects are always going to be in the same order. I’d like to be able to remove all items in order from the start until a specific id is reached.

I thought I could do this by just looping through until one is found and then pushing the items coming after that to a separate array:

let skippedArray = []

let skipUntilIndex = undefined

test.forEach((item, i) => {
  if(item.id === 'b') {
    skipUntilIndex = i
  }
  if(skipUntilIndex && i >= skipUntilIndex) {
    skippedArray.push(item)
  }
})

// [
//   {
//     id: 'b',
//   },
//   {
//     id: '5',
//   },
//   {
//     id: 'c',
//   },
//   {
//     id: '7',
//   },
// ]
console.log(skippedArray)

But this seems pretty dirty. Is there a better way to achieve this? I don’t mind using lodash or similar libraries.

Uncaught TypeError: Cannot read properties of undefined (reading ‘rendered’)

im newbie in React and trying to make a headless worpdpress aplication.
when i fetch a post i get only the first value.

I fetch the post and save it in the state

componentDidMount() {
this.setState({ loading: true }, () => {
  axios.get('http://localhost/wpprojekte/ebike/wp-json/wp/v2/posts/426')
    .then(res => {
      this.setState({ loading: false, error: 'no error', post: res.data })
    }).catch(error => {
      console.log(error);
    });
});}

I have now the post in my state which looks like

constructor(props) {
super(props);
this.state = {
  loading: false,
  error: 'error',
  post: {},
}}

when i render the Component, i can get only the first value from the post.
for example this.state.post.date

when i try to get this.state.post.title.rendered

Uncaught TypeError: Cannot read properties of undefined (reading 'rendered')

here is The render function

render() {
return (
  <div>
    {<div dangerouslySetInnerHTML={{ __html: this.state.post.title.rendered }} />}
  </div>
)}

I dont understand why it is getting only the first value.

How can calculate automatically without click any button to run function

I want to calculate days of a reservation for a booking website.
I want to calculate total price (days*$100) automatically without click any button to run function but update auto with out refresh page.

function daysBetween(startDate, endDate) {
  var millisecondsPerDay = 1000 * 60 * 60 * 24;
  var startDateUTC = Date.UTC(startDate.getFullYear(), startDate.getMonth(), startDate.getDate());
  var endDateUTC = Date.UTC(endDate.getFullYear(), endDate.getMonth(), endDate.getDate());

  return Math.floor((endDateUTC - startDateUTC) / millisecondsPerDay);
}

document.getElementById("btn").addEventListener("click", function() {
  let startDate = new Date(document.getElementById("startdate").value);
  let endDate = new Date(document.getElementById("enddate").value);
  let output = document.getElementById("totalprice");

  // Get how much days is between these dates
  let days = daysBetween(startDate, endDate);

  if (days) {
    output.classList.remove("text-danger");
    output.innerHTML = `${days*100}€`;
  } else {
    /* if no valid date is entered */
    output.classList.add("text-danger");
    output.innerHTML = `Select valid dates`;
  }

}, false);
<section class="sec5">Check in</section>
<section class="sec2"><input class="date" id="startdate" type="date" name="checkin" required=""></section>

<section class="sec5">Check out</section>
<section class="sec2"><input class="date" id="enddate" type="date" name="checkout" required=""></section>


<p>Total price
  <p>
    <section class="sec3" id="totalprice" name="totalprice">--</section>



    <div id="btn">CLICK ME!</div>

PHP, jQuery, AJAX: Can insert one type of data to database

I have simple jQuery AJAX which from HTML form through PHP gets some data and makes it in the background.

Also, I’m using phone numbers this library.

Both scripts work fine but when all data are inserted into the database the phone number is not inserted.

When I try to use the form without Javascript, only with PHP script all data also with phone number is inserted.

In my opinion, the problem will be in AJAX and I can’t find it.

Is there any solution how I can fix it?

My code is on this link

Intercept 401 error and prevent console error message

I’m using the following library axios-auth-refresh to automatically refresh the token.

When I make a call to the API it returns a 401 error and in this way the library is triggered in order to execute the refresh token and ensure that all requests are successfully completed.

I’m using axios to make API calls and I also use interceptors. I’ve already tried to check if I get the 401 error in the response interceptor but that doesn’t happen, I always get the code 200.

Is there any way to prevent the 401 error in the browser?

Interceptors

axios.interceptors.request.use(request => {
  request.headers['Authorization'] = `Bearer ${sessionStorage.getItem("access_token")}`;
  return request;
});

axios.interceptors.response.use(function (response) {
  return response;
}, function (error) {
  return Promise.reject(error);
});

axios-auth-refresh

const refreshAuthLogic = (failedRequest) => {
   
    return axios.post(url,
    {
        client: "Test",
        grant_type: "refresh_token",
        refresh_token: sessionStorage.getItem('refresh_token')
    }).then(tokenRefreshResponse => {
        failedRequest.response.config.headers['Authorization'] = 'Bearer ' + tokenRefreshResponse.data.access_token;
        sessionStorage.setItem("access_token", tokenRefreshResponse.data.access_token);
        sessionStorage.setItem("refresh_token", tokenRefreshResponse.data.refresh_token);
        return Promise.resolve();
    }).catch(function (e) {
        console.log("error", e);
    });
}

createAuthRefreshInterceptor(axios, refreshAuthLogic);

simple get

private extractData(res) {
    return res.data;
  }

  private handleErrorPromisse(error: Response | any) {
    console.error(error.message || error);
    return Promise.reject(error.message || error);
  }

  GetSample(): Promise<any> {
    return axios.get(url, {
      headers: {
        Authorization: 'Bearer ' + sessionStorage.getItem("access_token")
      }
    })
      .then(this.extractData)
      .catch(this.handleErrorPromisse);
  }

problem

img

“RNSScreenStackHeaderConfig” was not found in the UIManager

i know this question has been asked before, (requireNativeComponent: “RNSScreenStackHeaderConfig” was not found in the UIManager when running android app, React Navigation Error, Invariant Violation: requireNativeComponent: “RNSScreenStackHeaderConfig” was not found in the UIManager) but none of the answers helped in solving my Problem.

Problem Description
Its pretty simple, i get the following Error when i start my react-native App on IOS:

ERROR  Invariant Violation: requireNativeComponent: "RNSScreenStackHeaderConfig" was not found in the UIManager.

My app.js

import React from 'react';
import Header from './components/header';
import { SafeAreaView } from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import { createNativeStackNavigator } from '@react-navigation/native-stack';

import homeScreen from './screens/home'

const Stack = createNativeStackNavigator();

function App(){
  return (
    <SafeAreaView>
      <NavigationContainer>
        <Stack.Navigator>
          <Stack.Screen name="Home" component={homeScreen} options={{ title: 'Welcome' }} />
        </Stack.Navigator>
      </NavigationContainer>
    </SafeAreaView>
  );
};

export default App;

It appeard after if followed this guide for navigating between Screens in react-native.

When removing const Stack = createNativeStackNavigator(); incl. the Stack.*** the Error also disappears. So i figured the Problem must be with that.

But due to me being a newbie to react-native, finding this Problem is quit hard.

Yes, i already tried the Solutions from the above mentioned Posts.

Thanks for any help,
Oliver

Why does chrome continue to give 404 errors for a file that’s not included anymore?

For a while, my website used to have two JS files, subtitle_tagline.js and lazysizes.min.js. A while back they were both folded into the main theme.js directly, and all the references to such were removed. Grepping for the file names in the final source produces zero results.

Chrome’s inspector still marks the requests it’s making as 404 (which is accurate), citing “(index)” as the initiator. Well, I can view source and Ctrl-f, and it’s most definitely not in there.

This shouldn’t be a caching issue, since I’ve cleared the entire cache multiple times, and dev tools are supposed to run in no-cache mode when they’re open regardless. Any ideas why a file with no references is still being requested?

EJS console.log() does print correctly, but it doesn’t while writing it to the table

Good Day everybody

If i use a console.log it prints it correctly, but it doesn’t write it to a table. And i have no idea why it doesn’t. Can someone help me please?

My EJS looks like this:

<% insrtdJngls.forEach((item) => { %>
                        <tr></tr>
                            <% console.log(item, "ejs print") %>
                            <% console.log(item.insrtdDateiname, "ejs print") %>
                            <td id="table_firma" class="tdList"><%=item.insrtdFirmaname%></td>
                            <td id="dateiname_table" class="tdList"><%=item.insrtdDateiname%></td>
                            <td id="table_time" class="tdList"><%=item.insrtdDateTime%></td>

                            <form method="post" action="/deleteOne">
                                <td><button class="DelOne"><img
                                            src="https://img.icons8.com/ios/25/000000/empty-trash.png" /></button></td>
                            </form>

                            <form method="post" action="/deleteAll">
                                <td><button class="DelAllBtn"><img
                                            src="https://img.icons8.com/fluency-systems-regular/25/000000/garbage-truck.png" /></button>
                                </td>
                            </form>
                            <% }); %>

And my ejs print looks like this:

{
  insrtdDateTime: 2022-01-12T01:18:00.000Z,
  insrtdDateiname: 'fantaWerbung',
  insrtdFirmaname: 'Fanta'
} ejs print
fantaWerbung ejs print
{
  insrtdDateTime: 2022-01-13T01:18:00.000Z,
  insrtdDateiname: 'fantaWerbung',
  insrtdFirmaname: 'Fanta'
} ejs print
fantaWerbung ejs print

But in the td, there is no output at all… if i write it with just item, it shows me, that there is one object, can someone explain?

Why doesn’t it write to the table like fantaWerbung? Because obviously the data it receives is correct…

Thanks a lot
Mats Groeneweg

I am able to move into next step in antd step form even though i have added validation in react.js

I am able to move into next step in antd step form even though i have added validation in react.js
I have used default validation of antd form

 const steps = [
    {
      title: "Service Address",
      content: (
        <Form form={form}>
          <Card>
            <h1>Lead Information</h1>
                <Form.Item
                  rules={[{ required: true }]}
                  name={"first_name"}
                  label="First Name"
                >
                  <Input />
                </Form.Item>
                       </Card>
                          </Form>
     },
    {
      title: "Service Information",
      content: "Second-content",
    },

And this my map loop to return the steps

return (
    <>
      <Steps
        current={current}
      >
        {steps.map((item) => (
          <Step key={item.title} title={item.title} />
        ))}
      </Steps>
      <div className="steps-content">{steps[current].content}</div>
        {current < steps.length - 1 && (
              <Button type="primary" onClick={() => next()}>
                Next
              </Button>
        )}
 )
</>

Can some one please help me with This!
Thanks in Advance

Variable redeclaration in javascript [duplicate]

I have read that redeclaration of variables using let is not allowed in javascript.
If this is true, then how is it possible to redeclare a variable in block scope when it is already present in file scope using let in javascript?
Does this mean that file scope is not same as global scope?

let x = 10;
{
    let x = 2;
}
console.log(x)

The above code gives an output 10
But what I expected is an error
Kindly help me out in understanding this.

How can i emulate the scrolling of sites like Reddit, Twitter and LInkedIn with React?

I want the scroll effect where the sections on the sides scroll to the last, or dont scroll at all but the middle section keeps scrolling. I have seen something similar in reddit, twitter and linkedin.

Heres my code and an image of how it looks so far:

function Body() {
  return (
    <div className="Body">
      <div className="user-menu"></div>

      <main className="timeline">
        <div className="post-box"></div>
        <div className="post"></div>
        <div className="post"></div>
        <div className="post"></div>
        <div className="post"></div>
        <div className="post"></div>
        <div className="post"></div>
        <div className="post"></div>
      </main>

      <div className="discover">
        <div className="discover-box"></div>
        <div className="footer-box"></div>
      </div>
    </div>
  );
}

enter image description here

Recalculate pagination when filter request is applied

I have this React page generated by JHipster:

import ......

export interface IOrdersProps extends StateProps, DispatchProps, RouteComponentProps<{ url: string }> {}

export const Orders = (props: any) => {
  const [paginationState, setPaginationState] = useState(
    overridePaginationStateWithQueryParams(getSortState(props.location, ITEMS_PER_PAGE, 'id'), props.location.search)
  );

  const [searchNameParam, setSearchNameParam] = useState('');
  const lastSearchNameParam = useRef(searchNameParam);

  const [ordersList, setOrdersList] = useState<any>([]);
  const [itemsSize, setItemsSize] = useState<any>([]);
  const [tradesList, setTradesList] = useState<any>();
  const [twapList, setTwapList] = useState<any>();

  const getAllEntities = async () => {
    const page = paginationState.activePage - 1;
    const itemsPerPage = paginationState.itemsPerPage;
    console.log('Refreshing page: ' + page);
    const apiUrl = 'api/orders?page=' + page + '&size=' + itemsPerPage + '&searchNameParam=' + searchNameParam;

    const result = await axios.get<IOrders>(apiUrl);

    setOrdersList(result.data);
  };

  const sortEntities = () => {
    getAllEntities();
    const endURL = `?page=${paginationState.activePage}&sort=${paginationState.sort},${paginationState.order}`;
    if (props.location.search !== endURL) {
      props.history.push(`${props.location.pathname}${endURL}`);
    }
  };

  useEffect(() => {
    sortEntities();
  }, [paginationState.activePage, paginationState.order, paginationState.sort]);

  useEffect(() => {
    const request = async () => {
      const apiUrl = 'api/ordersCount';
      const result = await axios.get<IOrders>(apiUrl);
      setItemsSize(result.data);
    };
    request();
    getAllEntities();
  }, []);

  const sort = p => () => {
    setPaginationState({
      ...paginationState,
      order: paginationState.order === 'asc' ? 'desc' : 'asc',
      sort: p,
    });
  };

  const handlePagination = currentPage => {
    setTradesList(null);
    setTwapList(null);
    setPaginationState({
      ...paginationState,
      activePage: currentPage,
    });
  };

  const handleSyncList = () => {
    sortEntities();
  };

  const { match, loading, totalItems } = props;

  useEffect(() => {
    if (searchNameParam !== lastSearchNameParam.current) {
      handleSyncList();
      lastSearchNameParam.current = searchNameParam;
    }
  }, [searchNameParam])

  return (
    <div>    
          <div>    
              <Table>
                ............
                <thead>
                  <tr>
                    <th>                         
                      <div>
                        <span>Filter</span>
                        <input onChange={e => setSearchNameParam(e.target.value)}/>
                      </div>
                      ................                   
                  </tr>
                </thead>
                {ordersList && ordersList.length > 0 ? (
                <tbody>
                  {ordersList.map((orders, i) => (
                    
                  ))}
                </tbody>
                ) : (
                  !loading && <div className="alert alert-warning">No Orders found</div>
                )}
              </Table>

          </div>

          {/*{props.totalItems ? (*/}
          <div className={ordersList && ordersList.length > 0 ? '' : 'd-none'}>
            {/*<Row className="justify-content-center">*/}
            {/*  <JhiItemCount page={paginationState.activePage} total={totalItems} itemsPerPage={paginationState.itemsPerPage} />*/}
            {/*</Row>*/}
            <Row className="justify-content-center">
              <JhiPagination
                activePage={paginationState.activePage}
                onSelect={handlePagination}
                maxButtons={5}
                itemsPerPage={paginationState.itemsPerPage}
                totalItems={itemsSize}
              />
            </Row>
          </div>
        </Tab>
        <Tab eventKey={'Asset Volumes'} title="Asset Volumes" onSelect={() => {}}>
          <AssetVolumes />
        </Tab>
      </Tabs>

    </div>
  );
};

const mapStateToProps = ({ orders }: IRootState) => ({
  ordersList: orders.entities,
  loading: orders.loading,
  totalItems: orders.totalItems,
});

const mapDispatchToProps = {
  getEntities,
};

type StateProps = ReturnType<typeof mapStateToProps>;
type DispatchProps = typeof mapDispatchToProps;

export default connect(mapStateToProps, mapDispatchToProps)(Orders);

When I enter something into search area API request is made and new data is populated.
But pagination is not updated.
How I can force the pagination pages to be recalculated when I receive new pages of data with search criteria?

Avoid recurring ‘if’ verification to check if an object has property

I do know how to check if a property exists (hasOwnProperty, in, !== undefined, etc).

But I don’t know how to avoid to perform an action on this property if it doesn’t exist.

Is there a solution to avoid the if (property && action in my case) verification each time ?

Similar question : Javascript – how to avoid multiple if condition checks when checking if object has a property? Not really relevant in my case

const myFunction1 = myFunction2 = () => {};
const generateElement = (p) => {
  let div = document.createElement(p.tag);
  p.classes && (div.className = p.classes);
  p.style && (div.style.cssText = p.style);
  p.content && (div.innerHTML = p.content);
  p.appendIn && p.appendIn.appendChild(div);
  p.attribs && Object.entries(p.attribs).forEach((y) => {
    div.setAttribute(y[0], y[1]);
  });
  p.events && Object.entries(p.events).forEach((y) => {
    div.addEventListener(y[0], y[1], false);
  });
  return div
}

var newElem = generateElement({
  tag: 'div',
  classes: 'mydiv',
  id: 'id42',
  content: 'Hello world!',
  style: 'background:#ccc',
  attribs: {
    'tabindex': 0,
    'title': 'Title #1'
  },
  events: {
    'click': myFunction1,
    'mouseout': myFunction2
  },
  appendIn: document.body
});

How to partition an array from the server side

The bottom line is, I need to get an array of people who have entered the server (the name is entered before entering the site). I implemented it very badly, on the client side I create an array and on the server side the same array and they are transferred between each other, but the problem is that the array created on the client side is filled only in requests to the server, that is, in the local scope, to me you need to access it globally. Here’s the implementation:
Client part:

const userName = prompt("Enter your name:");
nameBlock.innerHTML = userName;

let arrayUser = []; // array of users

socket.emit('connect user', {
    userConnect: userName, // pass the name
    arrayConnect: arrayUser // we pass the array where we write the names
});

socket.on('connect user', (userName) => {
    arrayUser.push(userName.arrayConnect);
    const item = document.createElement('div');
    item.innerHTML = `User <b><span class = "user">${userName.name}</span></b> connected to the chat!`
    userConnect.append(item);
});

Server part:

let arrayUser = []; // create an array
io.on('connection', (socket) => {
    socket.on('chat message', (msg) => {
        io.emit('chat message', {
            message: msg.message,
            name: msg.name
        });
    });

    socket.on('connect user', (userName) => {
        arrayUser.push(userName.userConnect);
        console.log(arrayUser);
        io.emit('connect user', {
            name: userName.userConnect,
            arrayConnect: arrayUser
        });
    });