Error in render: “TypeError: _vm.$t is not a function” – Property or method “$t” is not defined on the instance but referenced during render

I’m using Vuetify (v2.3.13) and I want to install multilanguage with vue-i18n (v9.1.0).

I’m developing in Javascript and use option API for my component.

My main.js:

import Vue from 'vue'
import App from './App.vue'
import router from './router'
import vuetify from './plugins/vuetify'
import './plugins'
import store from './store'
import { sync } from 'vuex-router-sync'

Vue.config.productionTip = false

import { createI18n } from "vue-i18n";
import en from "./locales/en.json";
import pt from "./locales/pt.json";

sync(store, router)

// Create VueI18n instance with options
const i18n = new createI18n({
  locale: "en",
  fallbackLocale: "en",
  messages: { pt, en },
});

new Vue({
  router,
  vuetify,
  store,
  i18n,
  render: h => h(App),
}).$mount('#app')

My json file where the translation will be en.json:

{
  "languages": {
    "pt": "Portuguese",
    "en": "English"
  },
  "title": {
    "config": "Configuration"
  }
}

I want to call my dictionnary in my component but I have these errors: Error in render: “TypeError: _vm.$t is not a function” and Property or method “$t” is not defined on the instance but referenced during render.

My component:

<template>
  <h2>{{ $t('title.config') }}</h2>
<div>
    <select v-model="lang">
      <option value="en">English</option>
      <option value="pt">Portugeuse</option>
    </select>
</div>
</template>
<script>
  export default {
     name: 'MyComponent',
     data: () => ({
      lang: "en"
    })
}
</script>

As I understand, I need to initialize or import the dictionnary into my component ?
Or my component doesn’t understand the $t because the internationalization is not installed well ?

How should I initialize the dictionary in my component ?

Getting nested array Index from an _id in mongo

This seems to be the season at work where mongo stumps me all the time. I will be given an item array index and a call._id. Not the call array index. I need to somehow get the index for that call id.So far I’ve been unable to do this. I’ve tried using arrayFilters and I also tried $indexOfArray.

use mydb

var lineNum = 0;
var callId = ObjectId("MY ID HERE");

var query = {
    "items.calls._id":callId
              
};

var update = {
     "$set": {
            
            //THIS WORKS
            [`items.${lineNum}.updatedTs`] : new Date(),
            
            //THIS DOES NOT WORK
      
            [`items.${lineNum}.calls.$[items.calls._id].message.takenBy.firstName`]: "Dani",

        }
        
};

var options = {
    multi: true, 
    arrayFilters: [
        {"items.calls._id", callId}
    ]
};

db.getCollection("myCollection").update(query,update,options);

What am I missing? For this example the callIndex should be: 0 but I am getting

"errmsg" : "BSON field 'update.updates.arrayFilters.0' is the wrong type 'string', expected type 'object'",
    "code" : 14,

I’ve been at this for days now. This is just my most recent attempt. I must be missing something with the way arrays filters work.

Passsing a value from an ASP cshtml into through js script to a controller

Context:

I have ASP.NET CORE 6 project.

I have added a button into a table that displays users. This button fires a modal window that later on would have a short snippet of logic (resetting the password of the user).

Need:

The modal window actually fires and is working for each row, but I am not able to pass a parameter from a table’s row button into a controller.

View (.cshtml):

<table class="table xtable-striped">
    <thead>
        <tr>
            ...
        </tr>
    </thead>
    <tbody class="tablealtrow">
        @foreach (var user in Model)
        {
            <tr>
                <td>@user.UserName</td>
                    ...
                <td>
                    <a class="btn btn-primary" id="btnShowModal">Reset Password</a>
                </td>
            </tr>
        }
    </tbody>
</table>

...

<div class="modal fade" id="Modal">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-body" />
        </div>
    </div>
</div>

<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script type="text/javascript">
    $(document).ready(function () 
    {
        $('[id*=btnShowModal]').on("click", function () 
        {
            $.get("@Url.Action("ResetPassword","UserRoles",
                function (data) 
                { 
                    $('.modal-body').html(data); 
                })
            $("#Modal").modal('show');
        });
        $("#btnHideModal").click(function () 
        {
            $("#Modal").modal('hide');
        });
    });
</script>

The model:

Probably would have a UserIdentity and UserManager instances, but for a while I make it simple.

public class ResetPasswordModel
{
    public int Id { get; set; }
    public string Name { get; set; }
}

The controller:

Here I am creating a ResetPasswordModel with a dummy data, but would expect to get a user id here from the view.

public IActionResult ResetPassword()
{
    return PartialView("ResetPassword", new ResetPasswordModel() { Id = 1, Name="TESTTESTTEST" });
}

The modal view model:

There would be logic of resetting the password after user clicks Reset button. Also the temporary password would be displayed. I would manage this logic on my own.

@model ResetPasswordModel

<p>You are about to reset the password for the user: @Model.Name</p>

<a class="btn btn-secondary" data-dismiss="modal">Close</a>
<a class="btn btn-primary">Reset</a>

Already tries:

I was not able to manage it, despite many tries. Among others:

  • use $.ajax instead of $.get.
  • set attribute data-user-name="@user.UserId" on a button
  • tried to get the value somehow through the view element instance into a js variable and pass it to action:
    CONTROLLER:
    public IActionResult ResetPassword(string parameterUSERID)

    JS SCRIPT:
    var parameterTEST = $('#userId').val;
    var parameterTEST  = $(this).data('user-name');
    $.get("@Url.Action("ResetPassword","UserRoles", new { parameterUSERID = parameterTEST  })", ... )

Sorry for an amateur question like that. This is actually my first JS task.

How to persist the state of a Redux reducer in the browser

In a Redux app the user can define a “reducer” for taking in a state object and an action object and returning the updated state. When the state corresponds to UI elements that configure how the app works, it’s useful to persist them between page reloads. How can this be done?

const initialUiConfigState = {"a": "1", "b": "2"};

// Performs the action onto the state and returns the updated state.
export function uiConfigReducer(state=initialUiConfigState, action) {
  switch(action.type) {
    case ACTION1:
      return {
        ...state,
        b: "3",
      };
    default:
      return state;
  }
}

React Native WebView not showing the full height

I am trying to render the full height of the website using the web view, it is not working as expected. A small portion of the bottom is getting cut off. It’s happening because of the paddingHorizontal in the main view. I am able to see the full website if I remove that padding. How do I solve this issue, I cannot delete that padding.

return (
    <SafeAreaView style={{}}>
      <TopBar navigation={navigation} isHome={true} />
      <ScrollView contentContainerStyle={{}}>
        <Text> dsdsdsdsddss </Text>
        <View style={{height:200}}></View>
        <View style={styles.mainview}>
          <View style={styles.container}>
            <WebView
              contentInset={{bottom: 20}}
              bounces={false}
              style={{height: webViewHeight}}
              onMessage={onWebViewMessage}
              scrollEnabled={false}
              source={{
                uri: url,
              }}
              onShouldStartLoadWithRequest={onShouldStartLoadWithRequest}
              injectedJavaScript={`
        const height = Math.max(document.documentElement.clientHeight, document.body.scrollHeight, document.documentElement.scrollHeight, document.body.offsetHeight, document.documentElement.offsetHeight);
        window.ReactNativeWebView.postMessage(height.toString());
      `}></WebView>
     
          </View>
          <View style={{height:200, backgroundColor:"red"}}></View>
        </View>
      </ScrollView>
    </SafeAreaView>
  );
};

const styles = StyleSheet.create({
  mainview: {
    paddingHorizontal: 16, //This padding is causing the issue
    paddingVertical: 24,
    flex: 1,
  },
  container: {
    backgroundColor: COLORS.white,
    borderRadius: 4,
    elevation: 5,
    shadowColor: COLORS.black,
    shadowOffset: {
      height: 4,
      width: 0,
    },
    shadowOpacity: 0.07,
    shadowRadius: 15,
  },
});

The JavaScript drawing line doesn’t fit on the cursor [duplicate]

when I draw on my canvas, the line doesn’t follow the cursor, the line is at another point away from the cursor. for example, if I draw at point A, the cursor will stay at point A but the line I draw can be at point b.

I think this is happening because I want to make the canvas area (drawing area) larger, because if the canvas is the default size this won’t happen

const paintCanvas = document.querySelector('.js-paint');
const context = paintCanvas.getContext('2d');
context.lineCap = 'round';

const colorPicker = document.querySelector('.js-color-picker');
const clearButton = document.querySelector('.js-clear-canvas');

clearButton.addEventListener('click', () => {
    context.clearRect(0, 0, paintCanvas.width, paintCanvas.height);
});

colorPicker.addEventListener('change', event => {
    context.strokeStyle = event.target.value;
});

const lineWidthRange = document.querySelector('.js-line-range');
const lineWidthLabel = document.querySelector('.js-range-value');

lineWidthRange.addEventListener('input', event => {
    const width = event.target.value;
    lineWidthLabel.innerHTML = width;
    context.lineWidth = width;
});

let x = 0, y = 0;
let isMouseDown = false;

const stopDrawing = () => { isMouseDown = false; }
const startDrawing = event => {
    isMouseDown = true;
    [x, y] = [event.offsetX, event.offsetY];
}
const drawLine = event => {
    if (isMouseDown) {
        const newX = event.offsetX;
        const newY = event.offsetY;
        context.beginPath();
        context.moveTo(x, y);
        context.lineTo(newX, newY);
        context.stroke();
        //[x, y] = [newX, newY];
        x = newX;
        y = newY;
    }
}

paintCanvas.addEventListener('mousedown', startDrawing);
paintCanvas.addEventListener('mousemove', drawLine);
paintCanvas.addEventListener('mouseup', stopDrawing);
paintCanvas.addEventListener('mouseout', stopDrawing);
.canvas {
    background-color: white;
    margin-top: 50px;
    margin-left: 25px;
    width: 100vh;
    height: 70vh;
    border-radius: 20px;
    border: 10px #208cff solid;
    box-shadow: 0px 0px 15px inset grey, 0px 0px 15px #0263ca;
}

.canvas .paint-canvas {
    display: block;
    width: 100vh;
    height: 70vh;
}

.canvas .paint-canvas:hover {
    cursor: crosshair;
}

.canvas .top {
    display: inline;
    
}
<!-- Canvas -->
    <div class="canvas">
        <h1>Scratch Here</h1>
        <input type="color" class="js-color-picker color-picker">

        <div class="top">
            <input type="range" class="js-line-range" min="1" max="72" value="1">
            <label class="js-range-value">1</label>Px
        </div>

        <canvas class="js-paint  paint-canvas" width="600" height="300"></canvas>
        <button class="js-clear-canvas">Clear Canvas</button>
    </div>

I received cookies but cookies were not in the list

I fetched a request to cross-origin and the server responsed with Set-Cookie headers.
https://i.stack.imgur.com/0oqFF.png

https://i.stack.imgur.com/PICj3.png

So I looked up the cookie list in the application tab of Chrome DevTools, but they were not in the list.

https://i.stack.imgur.com/S9hPE.png

I set Access-Control-Allow-Origin correctly(not *, definitely), so I don’t know why this happened.

I found out the allowed origin is https://abcde.fgh.ij << kinda like this stuff,
but the partition key is https://fgh.ij

Is it a correct partition key to use cookies?

Css is not working properly whenever I use lazy loading in React

I was making application with default react imports, then I found out that lazy loading could help my react application in working faster and added It inside my code but for some reason it broke CSS code. widths and heights as well as positions are not same as they were before. Pls help.

I tried to clean Browser cache and restart react application but didn’t help

Input type=”tel” pattern stopped working after Chrome 114 [duplicate]

I have a HTML form with a telephone input. I have created a regex pattern that I believe suit my needs.

<input type="tel" pattern="(+d{2})?[-. ]?[0-9]{3}?[-. ]?([0-9]{3})[-. ]?([0-9]{4})"/>

The pattern is correct, according to my understanding.

However, if you test it with an erroneous value like qqqqq, the field validation succeeds and the form is posted, since Chrome version 114. With Chrome versions up to 113, the validation failed saying, Please match the requested format. If you switch the pattern to something simpler like [0-9]{10}, the validation works normally.

Am I missing something, or is this a bug in Chrome?

1: https://regex101.com/r/WWKtna/1

Svelte cannot import

Im a svelte beginner and im trying to do simple feedback app, i have 2 files one with app and second with list of feedbacks
App.svelte

<script>
  import feedback from "./components/feedbacks.svelte";
</script>

<main>
  <p>{feedback}</p>
</main>

<style>
</style>

feedbacks.svelte

<script>
    export let feedback = [{text: 'Its good', rate: 7}, {text: 'alright', rate: 6}, {text: 'terrible', rate: 2}];
</script>

instead of an array it returns me
class Feedbacks extends SvelteComponentDev { constructor(options) { super(options); init(this, options, instance$1, create_fragment$1, safe_not_equal, { feedback: 0 }); dispatch_dev(“SvelteRegisterComponent”, { component: this, tagName: “Feedbacks”, options, id: create_fragment$1.name }); } get feedback() { throw new Error(“: Props cannot be read directly from the component instance unless compiling with ‘accessors: true’ or ‘<svelte:options accessors/>'”); } set feedback(value) { throw new Error(“: Props cannot be set directly on the component instance unless compiling with ‘accessors: true’ or ‘<svelte:options accessors/>'”); } }

React Handle server side validation error message

For my React app, I have a Yup validation schema defined as below;

export const mySchema = {
    ['my-add']: yup.object().shape({
        'myId': yup
            .string()
            .nullable()
            .required()
            .max(9, `Max length 9`)
            .test(
                'api-error',
                '${serviceErrorMsg}',
                async function(value, ctx) {
                    console.log(value);
                    console.log(ctx);
                    const {
                        isServiceError,
                        serviceErrorMsg
                    } = this.options.context;
                    if (isServiceError) {
                        return false;
                        //return ctx.createError({ path: 'myId', message: serviceErrorMsg }); //Not able to do this for some reason, 
                    }
                    return true;
                    
                }
            )
    })
}

I want to validate ‘myId’ field based on API response and accordingly display error message below the field if server gives me validation error for this field.

In my consuming component, I have

const {triggerValidation, setError} = useForm({});
//...
//...API call
    const context = { isServiceError: response.errorFlag, serviceErrorMsg: response.errorMessage};
    await mySchema['my-add'].validate(props.formRef.current.getValues(), {context}).catch((err) => {
        // logging err here gives below
        setError('myId', 'api-error', response.errorMessage); 
    });

Logging “err” in the catch block gives below

ValidationError: undefined
    at createError (createValidation.js?f6e7:42:1)
    at eval (createValidation.js?f6e7:60:71)

Now, with the setError under the catch, I can see the error message displayed below the field.
However, I am not sure if this is the correct way to handle/display the validation error message.

I was instead wanting/trying to display the error message via
ctx.createError() in my Yup definition, as I have shown in the commented code. But, that does not work for some reason.

Please comment if handling the validation error in the catch block, the way I have done here is correct.

P.S: I am using a wrapper library based on React Hook Forms similar to Formik in my app.

Is there a General Implementation of the General Update Pattern

Is there a library or “well-known” implementation for the General Update Pattern (known from d3) for e.g. two arrays. d3 only applies it to HTML Elements and a data array.

Something similar to this:

const state = [{id:1, data:"foo", data2:"foo"}, {id:2, data:"bar"}]
const change = [{id:1, data:"baz"}, {id:3, data:"qux"}]

const nextState = select(state, entry => entry.id)
    .update(change, entry => entry.id)
    .join(
        enter => enter,
        update => update,
        exit => {}
    )
    .each(function (d) {Object.assign(this, d)})
    .value()

console.log(nextState)
// [{id:1, data:"baz", data2:"foo"}, {id:3, data: "qux"}]


function select(state, keyF) {
    const stateMap = new Map()
    state.forEach(entry => stateMap.set(keyF(entry), entry))
    let changeMap = new Map()

    const selection = {
        update(change, keyF) {
            change.forEach(entry => changeMap.set(keyF(entry), entry))
            return selection
        },
        join(enterF, updateF, exitF) {
            // ...
            return selection
        },
        each(callback) {
            stateMap.forEach((current, key) => callback.call(current, changeMap.get(key), key, state))
            return selection
        },
        value() {
            return stateMap.values()
        }
    }
    return selection
}