Utilize the ternary operator to swap out image URLs based on certain conditions being fulfilled

Is it possible to change an image and have it stay rendered when the phone is shaken? Currently, I am able to change the image on shake but it reverts back once the condition is not met:

function Shaker(){
useEffect(() => {
        const subscription = accelerometer.subscribe(({ x, y, z }) =>
            setSensorData({ x, y, z })    
        );  
}, []);

const acceleration = Math.sqrt(sensorData.x * sensorData.x + sensorData.y * sensorData.y + sensorData.z * sensorData.z);
const imgChange = acceleration > 12 ? 'imgThatIWantToRenderAfterConditionAndStay.png' : 'DefaultImg.png' ;
return (
        <View>
            <Image style={{ width: 100, height: 100 }} source={{ uri: imgChange }} />
        </View>
}

When I tried using a boolean instead of acceleration > 12, I encountered a read-only error:

let accelerationObtained = false;
if (acceleration > 12) { accelerationObtained = true; }
const ifImg = accelerationObtained ? imgUri : 'https://www.nicepng.com/png/full/416-4167329_shot-glass.png' ;

I feel like my solution is not ideal and would like to learn a better way to handle this scenario.

Answer №1

The reason for the error is your attempt to reassign a new value to accelerationobtained, which has been declared as a const:

A const declaration creates a reference that cannot be changed or reassigned
Source

You can instead use

let accelerationobtained = false;
:

let accelerationobtained = false;
if (acceleration > 12) { accelerationobtained = true; }
const ifimg = accelerationobtained ? imguri : 'https://www.nicepng.com/png/full/416-4167329_shot-glass.png' ;

However, consider whether it's really necessary. If you only use it once, you can simplify by directly comparing acceleration in the ternary statement:

const ifimg = acceleration > 12 ? imguri : 'https://www.nicepng.com/png/full/416-4167329_shot-glass.png' ;

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

Using the return statement to set a value from a callback function in TypeScript

As I retrieve data from an array of class People, each person has an attendance list represented by Observable<any[]>. // Defining the Person class class Person { id: number; name: string; attendance: Observable<any[]>; // Represents ...

What is the correct way to specify the data type for the useState hook when I intend to store an array of objects?

My dilemma involves storing an array of objects using the useState hook, but I am struggling with the syntax required to describe the expected type. The type that I want to store is Array<Updates>. Below is the code I have: const [messages, setMessa ...

"Upgrade alert: Jump to the latest version of reactive, version 18

Attempting to create a react-app using npx create-native init project, but encountering React version 17.0.2. Following the upgrade guide at https://reactjs.org/blog/2022/03/08/react-18-upgrade-guide.html, I used npm install react react-dom to update to th ...

Exploring the synergy between radio buttons and the Next JS framework

To highlight an issue I encountered in a Next JS app, I decided to create a test app named radio-flash-test. Here are the commands I used to create the app: % npx create-next-app@latest ..... % cd radio-flash-test % heroku create radio-flash-test The ...

What would be a colloquial method to retrieve the ultimate result from the iterator function?

I've got a rather complex function that describes an iterative process. It goes something like this (I have lots of code not relevant to the question): function* functionName( config: Config, poolSize: number ): Generator<[State, Step], boo ...

The Angular test spy is failing to be invoked

Having trouble setting up my Angular test correctly. The issue seems to be with my spy not functioning as expected. I'm new to Angular and still learning how to write tests. This is for my first Angular app using the latest version of CLI 7.x, which i ...

Retrieve the status callback function from the service

Can anybody show me how to set up a call-back function between a component and a service? I apologize for my lack of experience with Angular and TypeScript. getDiscount(){ let getDisc = []; getDisc.push({ price: Number(this.commonService.getP ...

Steps for displaying a new event on a fullCalendar

Utilizing fullCalendar to display a list of events in the following manner: this.appointments = [{ title: "Appointment 1", date: "2020-09-06", allDay: false }, { title: "Appointment 2", date: "2020 ...

Angular with Firebase: How to ignore a field in a query

I am curious to see if my current structure is compatible with Firebase, or if I need to make adjustments. Let's take a look at an example using the "/rooms" endpoint, which contains an array of Room objects: export class Room { id: number; p ...

Explore the functionality of a TypeScript-created Vue component by testing it with Vue-test-utils

In my attempt to validate props with various data types in a Vue component (built using TypeScript), I utilized the Vue-test-utils package. Despite implementing expect().tobe(), there remains an untested line: DropDownList.vue <template> <v-sel ...

Tips for utilizing mergeWith with Subjects in an Angular application

Objective: Creating a Combined Filter with 3 Inputs to refine a list Conditions: Users are not required to complete all filters before submission The first submit occurs when the user inputs data Inputs are combined after more than one is provided Appro ...

Tsc encounters issues when interacting with AWS services

When attempting to compile TypeScript code into JavaScript using tsc, I encountered constant crashes specifically related to AWS code within the node_modules directory. Despite my efforts to resolve the issue by adding skipLibCheck to my tsconfig file, inc ...

Sending template reference from one Angular component to another

I have a main grid component that includes smaller grid-item components. The majority of these grid items navigate to a specific route when clicked. However, there is one particular item that should open a modal window instead of navigating. Is there a wa ...

Creating an NPM package that utilizes global types without altering the project it is integrated with

The Dilemma: When working on a project that involves reusing multiple types across various files, utilizing types defined in a script file can be advantageous. These global types are accessible throughout the entire project without the need for importing, ...

TS2304: The build process is unable to locate the name 'iterable' within @types

As an experienced dog attempting to master new tricks like npm and TypeScript, I find myself faced with a challenge in my Visual Studio 2017 project. Despite setting it to "Latest" TypeScript 2.5 and adding @types/jquery (3.2.12), the project keeps throwin ...

I am interested in utilizing the request-reply pattern with KafkaJS in a TypeScript environment. Could you provide guidance on how to successfully implement this?

I am new to Kafka and I am trying to implement the request-reply pattern using kafkajs in TypeScript. However, my current implementation is very basic and the consumers inside producers are taking too long to start, causing delays. Is there a better way to ...

How to revert TypeScript version in Visual Studio to 1.7

After updating VS2015 to Update 2, which also updated TypeScript to version 1.8, I encountered some issues with my code that required me to uninstall it. However, rolling back Update 2 did not revert TypeScript back to the previous version. Despite TypeScr ...

Navigate to a different page using the A-g Grid router when a row is

Having trouble making the router link interact with Ag grid. When I use the router link ="url", it always takes me to a different page every time I click on anything in the grid. What I really want is for clicking on an individual row to redirect me to an ...

Type of tuple without a specific order

Exploring Typescript typings has led me to ponder how to create a type that is a tuple with unordered element types. For example: type SimpleTuple = [number, string]; const tup1: SimpleTuple = [7, `7`]; // Valid const tup2: SimpleTuple = [`7`, 7]; // &ap ...

Using TypeScript's `extend` keyword triggers an ESLint error when attempting to extend a generic type

I am dealing with numerous models that include additional meta data, which led me to create a generic type for appending them to the models when necessary: type WithMeta<T> = T extends Meta; However, I encountered an error stating: Parsing error: &a ...