reactjs – how to call render after submit

I’m making crud system with react, spring boot

if I type message and enter.

whole message board are gone.
but if I refresh the browser, it print well.
I logged a lot, so I found that if I submitted it, react call render() before taking data from axios.
how can I fix it?

 handleSubmit = async(e) => {
e.preventDefault();
const formData = new FormData();
formData.append("content", this.state.content);

// axios.post("http://localhost:3000/post/upload", formData).then((posts) => {
//   this.setState({ posts: posts.data });
// });
const p = await axios.post("http://localhost:3000/post/upload", formData);
await this.setState({posts: p.data});
console.log("제출");

}

enter image description here


enter image description here

Optimizing GL render

I have two questions :

1- I’m sending different Uniform Buffer Objects (UBO) to different programs, would it be (and how much of) an improvement to combine all the UBO into a single big one that is linked to all programs ?

2 – I’m drawing to thirty two 1920×1200 textures, my max_texture_size is 16384, would it be (and how much of) an improvement to single drawcall to an atlas ?

magento2 – Render HTML in form_additional_info position in customer edit page

I need to display a custom customer field at form_additional_info position in the edit.phtml template.

The default edit.phml contains this instruction:

<?= $block->getChildHtml('form_additional_info') ?>

So, in my custom customer_account_edit.xml file I had:

<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceBlock name="customer_edit">
            <block class="MagentoFrameworkViewElementTemplate"
                   name="form_additional_info"
                   template="Vendor_Core::customer/additionalinfocustomer.phtml"/>
        </referenceBlock>
    </body>
</page>

however, my custom template is not shown.

By seeing the default customer_account_edit.xml file, this is the content:

<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <update handle="customer_account"/>
    <body>
        <referenceBlock name="head.components">
            <block class="MagentoFrameworkViewElementJsComponents" name="customer_account_edit_head_components" template="Magento_Customer::js/components.phtml"/>
        </referenceBlock>
        <referenceBlock name="page.main.title">
            <action method="setPageTitle">
                <argument translate="true" name="title" xsi:type="string">Edit Account Information</argument>
            </action>
        </referenceBlock>
        <referenceContainer name="content">
            <block class="MagentoCustomerBlockFormEdit" name="customer_edit" template="Magento_Customer::form/edit.phtml" cacheable="false">
                <container name="form.additional.info" as="form_additional_info"/>
            </block>
        </referenceContainer>
    </body>
</page>

So I thought I should reference customer_edit block and define form.additional.info block inside, but it did not work.

Any help?

node.js – Tem como usar as variáveis do EJS com o método “redirect” do express ao invés do render?

Segue o exemplo de uma página html (index.ejs) com uma mensagem escrita “Verificar senha” e um formulário com um input e um botão. Quero que, ao preencher esse input com uma senha e fizer a requisição, ele seja redirecionado para a mesma página, porém com a mensagem modificada para “Senha correta” ou “Senha errada”, dependendo do que for digitado. O problema é que essas variáveis só podem ser mandadas pelo método render, e não pelo redirect.

A senha correta é “123”.

Os pacotes necessários pra rodar são: express, ejs.

Index.ejs:

 <form action="/verify" method="POST">
   <input type="password" name="password">
   <button>Enviar</button>
 </form>
 <p>
   <%=passStatus%>
 </p>

Index.js:

const express = require("express");
const app = express();
const path = require("path");
app.use(express.urlencoded({ extended: true }));

// EJS Settings
app.set("view engine", "ejs");
app.set("views", path.join(__dirname, "views"));

// Routes
app.get("/", (req, res) => {
  res.render("index", { passStatus: "Verificar senha" });
});

app.post("/verify", (req, res) => {
  let corectPass = 123;
  let verifyPass = req.body.password;
  if (corectPass == verifyPass) {
    res.redirect("/");
    // Pensei em algo assim ↓, mas a "passStatus" só funciona com o método ".render".
    // res.redirect("/", {passStatus: "Senha correta"});
  } else {
    res.redirect("/");
    // Pensei em algo assim ↓, mas a "passStatus" só funciona com o método ".render".
    // res.redirect("/", {passStatus: "Senha errada"});
  }
});

app.listen(5000, () => {
  console.log("Servidor Rodando na porta 5000");
});

8 – Programatically render a block in a twig template

I need to render a views block in my page.html.twig template. In D7 I would do this:

<?php
  $block = module_invoke('module_name', 'block_view', 'block_delta');
  print render($block('content'));
?>

In Drupal 8 module_invoke is deprecated and recommended to use this: (I’ve added the block’s name as the second parameter)

Drupal::moduleHandler()->invoke($block, 'views_block__blog_block_1', $args = array());

I tried a few things. First tried to do it in a twig template but I don’t know how to call php functions in a twig template, so that didn’t turn out too well.

Then I called the function in the preprocess_page() function in the .theme file but before I could get it to work I tried something simpler just to try make a variable work inside the twig template which didn’t work either, for example:

In the template_preprocess_page(&$vars) function in the .theme file:

$test = 'Hello World';
$vars('$my_var') = $test;

I tried to call my_var inside the twig template but it didn’t work and I got an error message saying “The site has an error, please contact the administrator”

So, to summarize, here are my questions:

  1. How do I make variables available inside twig templates?
  2. How do I call functions inside twig templates?
  3. Do I render blocks inside the .theme file or twig template?

javascript – Which of these approaches is better to load and render data in a browser based, turn based game?

I am developing a browser-based, turn-based board game. When a player accesses the page, the game current status is loaded from the database and the board is rendered accordingly. I am not sure which of the following approaches is better. For simplicity, let’s suppose that the only parameter that has to be loaded and rendered is a number that can be either 0 or 1.

Approach #1:

<?php
    $param = load_game_data(); // in the real case, this will be an associative array with many parameters
?>
<html>
<head></head>
<body>
<div id="board">
<!-- html elements related to the board -->
</div>
<script>
// as an example, the loaded data determines the bg color
document.getElementByID("board").style.backgroundColor = 
<?php if($param == 0) echo('"red"'); else echo('"green"'); ?>
;

</script>
</body>

Approach #2:

<html>
<head></head>
<body>
<div id="board">
<!-- html elements related to the board -->
</div>
<script>
$.ajax({
   url: "load_game_data.php",
}).done(function(param){
   if(param == 0)
        document.getElementByID("board").style.backgroundColor = "red";
   else
        document.getElementByID("board").style.backgroundColor = "green";
});
</script>
</body>

What are the pros and cons of the two approaches? What is the standard way to proceed? Note that the user can interact with the board elements (e.g. check information about some of them or change their status) but permanent changes are saved to the DB only when the turn ends.

Render Issues for R Markdown HTML Output to Sharepoint

So I’ve finished a lovely R Markdown script with an HTML output and was excited to share the analysis to colleagues internally, by sharing the Sharepoint link.

The output works fine when I open the HTML file directly on my machine. But for whatever reason, when I share or view via the Sharepoint link, simple things like the TOC, plotly graphs and leaflet maps do not render.

Here’s an example of the problem I’m running into, with some really basic script just as an example.

---
title: "Test_Output"
output: 
  html_document:
    toc: true
    toc_float: true
    
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

## R Markdown
Hello, this is a test.

## Test
```{r test plotly, echo = FALSE, warning = FALSE, message = FALSE}
library(plotly)
plot_ly(data = iris, x = ~Sepal.Length, y = ~Petal.Length)
```

And so this is the output, right.

enter image description here

But when I share the link (something like this https://mycompany.sharepoint.com/:f:/s/mydepartment/EvLlZjmxOetc) or if someone were to try and just navigate to the page on our Sharepoint, the output is all messed up. It looks like this: plots and TOC and maps do not render.

enter image description here

If anyone can help me to figure out how to allow my Markdown HTML output to render instantly once I share the link, that would be incredible, and I would feel like all my work on the script was not in vain!

I’ve tried adding “download=1” to the end of the URL, which indeed gives users an ability to view the output correctly by clicking the link and downloading the HTML, but this is not optimal as this is supposed to be a live product that I will continue updating.

Thanks! C

web – How do the Render Engine and JavaScript Engine Communicate in a browser?

I’m looking for a detailed answer on this.

What I already Know

So I have some understanding about the call stack and callbacks, and that the browser add functionality through web APIs which add callbacks through the event loop. I also read somewhere about the JS engine having an API.

What I want to understand

How are the web APIs exposed to the JS engine? (If this is about the JS engine having an API, some description on how that API works would do)

How can the behavior of the Render Engine be manipulated through JavaScript, like manipulating the DOM, CSSOM etc.? (If I understood correctly, this is the equivalent of asking how web APIs work)

Thanks!

magento2 – How to render related products block using a php script?

I’ve created the below code, but it looks like I’m missing something. Can you help please?

<?php

require __DIR__ . '/../../app/bootstrap.php';
$bootstrap = MagentoFrameworkAppBootstrap::create(BP, $_SERVER);
/** @var MagentoFrameworkObjectManagerObjectManager $objectManager */
$objectManager = $bootstrap->getObjectManager();

$state = $objectManager->get('MagentoFrameworkAppState');
$state->setAreaCode('frontend');

$registry = $objectManager->get('MagentoFrameworkRegistry');
$pageFactory = $objectManager->get('MagentoFrameworkViewResultPageFactory');

$productFactory = $objectManager->get('MagentoCatalogModelProductFactory');
$product = $productFactory->create()->load(143767);
$registry->register('product', $product);
$resultRedirect = $pageFactory->create();

echo $resultRedirect->getLayout()
    ->createBlock("MagentoCatalogBlockProductProductListRelated")
    ->setTemplate("Magento_Catalog::product/list/items.phtml")
    ->setData('type', 'related')
    ->toHtml();

(Magento version is 2.4.2). The problem is:

Fatal error:  Uncaught TypeError: Argument 2 passed to MagentoCatalogBlockProductImageFactory::getLabel() must be of the type string, null given, called in /var/www/html/app/code/Magento/Catalog/Block/Product/ImageFactory.php on line 168 and defined in /var/www/html/app/code/Magento/Catalog/Block/Product/ImageFactory.php:117
Stack trace:
#0 /var/www/html/app/code/Magento/Catalog/Block/Product/ImageFactory.php(168): MagentoCatalogBlockProductImageFactory-&gt;getLabel()
#1 /var/www/html/generated/code/Magento/Catalog/Block/Product/ImageFactory/Interceptor.php(23): MagentoCatalogBlockProductImageFactory-&gt;create()
#2 /var/www/html/app/code/Magento/Catalog/Block/Product/ImageBuilder.php(135): MagentoCatalogBlockProductImageFactoryInterceptor-&gt;create()
#3 /var/www/html/app/code/Magento/Catalog/Block/Product/AbstractProduct.php(518): MagentoCatalogBlockProductImageBuilder-&gt;create()
#4 /var/www/html/app/code/Magento/Catalog/view/frontend/templates/product/list/items.phtml(216): MagentoCatalogBlockProductAbstr in /var/www/html/app/code/Magento/Catalog/Block/Product/ImageFactory.php on line 117

theming – How can I render the chart inside the container ?

I am running Drupal 9 on Lando. I installed the Charts and the Highcharts modules. I made a custom module with a template file containing the following code.

{# stats_degrees/templates/mychart-template.html.twig #}
{{ attach_library('stats_degrees/highcharts') }}
<h1>My Chart Template</h1>

<div id='container' style='width:100%;height:100%;'></div>

This is the render array output by the controller class.

 // build render array for chart
    $chart = array(
      '#attached' => array(
        'library' => array('stats_degrees/highcharts'),
      ),
      '#theme' => 'mychart_template',
      '#type' => 'chart',
      '#chart_type' => 'line',
      '#chart_library' => 'highcharts'
      '#title' => t($title),
      '#legend_position' => 'right',
    );

I then create the rest of the chart array and return it. The template is rendered with no chart.

How can I render the chart inside the container <div>?